#include using namespace std; const int N = 1100; const int inf = 1000000007; int l[N], r[N], dp[N][6]; int calc_step(int x, int y){ int t = abs(y - x); return (t + 1) >> 1; } int main(){ //freopen("a.in", "r", stdin); //freopen("a.out", "w", stdout); int i, j, k, T, n, ne_real_l, ne_real_r, real_l, real_r; scanf("%d", &T); while (T--){ scanf("%d", &n); for (i = 1; i <= n; i++){ scanf("%d%d", &l[i], &r[i]); } int ans = inf; memset(dp, 0x7f, sizeof(dp)); real_l = 1; real_r = 1000000; for (i = 1; i <= n; i++){ real_l = max(real_l, l[i]); real_r = min(real_r, r[i]); if (real_l > real_r){ break; } for (j = 1; j <= 4; j++){ int pos; if (j <= 2){ pos = l[i] + j - 1; } else{ pos = r[i] - (4 - j); } if ((pos < l[i]) || (pos > r[i])){ continue; } if ((pos >= real_l) && (pos <= real_r)){ dp[i][j] = 0; } } } if (i > n){ printf("0\n"); continue; } for (i = 1; i < n; i++){ for (j = 1; j <= 4; j++){ int pos; if (j <= 2){ pos = l[i] + j - 1; } else{ pos = r[i] - (4 - j); } if ((pos < l[i]) || (pos > r[i])){ continue; } int trans_to = i + 1; while ((trans_to <= n) && ((l[trans_to] <= pos) && (pos <= r[trans_to]))){ trans_to++; } if (trans_to > n){ ans = min(ans, dp[i][j]); continue; } else{ for (k = 1; k <= 4; k++){ int ne_pos; if (k <= 2){ ne_pos = l[trans_to] + k - 1; } else{ ne_pos = r[trans_to] - (4 - k); } if ((ne_pos < l[trans_to]) || (ne_pos > r[trans_to])){ continue; } dp[trans_to][k] = min(dp[trans_to][k], dp[i][j] + calc_step(pos, ne_pos)); } } } } for (j = 1; j <= 4; j++){ ans = min(ans, dp[n][j]); } printf("%d\n", ans); } return 0; }