#include using namespace std; typedef long long LL; typedef pair pii; #ifdef DEBUG #define display(x) cerr << #x << " = " << x << endl; #define displaya(a, st, n)\ {cerr << #a << " = {";\ for(int qwq = (st); qwq <= (n); ++qwq) {\ if(qwq == (st)) cerr << a[qwq];\ else cerr << ", " << a[qwq];\ } cerr << "}" << endl;} #define displayv(v) displaya(v, 0, (int)(v).size() - 1) #define eprintf(...) fprintf(stderr, __VA_ARGS__) #else #define display(x) ; #define displaya(a, st, n) ; #define displayv(v) ; #define eprintf(...) if(0) fprintf(stderr, "...") #endif template bool chmin(T &a, const T &b) { return a > b ? a = b, true : false; } template bool chmax(T &a, const T &b) { return a < b ? a = b, true : false; } const int INF = 0x3f3f3f3f; int solve() { int n; cin >> n; vector l(n), r(n); vector p; p.reserve(n * 4); for(int i = 0; i < n; ++i) cin >> l[i] >> r[i]; for(int i = 0; i < n; ++i) { p.push_back(l[i]); p.push_back(r[i]); if(l[i] < r[i]) p.push_back(l[i] + 1), p.push_back(r[i] - 1); } sort(p.begin(), p.end()); p.erase(unique(p.begin(), p.end()), p.end()); int m = p.size(); vector d(m, 0); for(int i = 0; i < n; ++i) { for(int j = 0; j < m; ++j) if(l[i] <= p[j] && p[j] <= r[i]) { // } else { d[j] = INF; } int odd = INF, even = INF; for(int j = 0; j < m; ++j) { if(p[j] % 2 == 0) { chmin(d[j], p[j] / 2 + even); chmin(d[j], p[j] / 2 + odd); chmin(even, d[j] - p[j] / 2); } else { chmin(d[j], p[j] / 2 + even + 1); chmin(d[j], p[j] / 2 + odd); chmin(odd, d[j] - p[j] / 2); } } odd = even = INF + (int)1e9; for(int j = m - 1; j >= 0; --j) { if(p[j] % 2 == 0) { chmin(d[j], even - p[j] / 2); chmin(d[j], odd - p[j] / 2 + 1); chmin(even, d[j] + p[j] / 2); } else { chmin(d[j], even - p[j] / 2); chmin(d[j], odd - p[j] / 2); chmin(odd, d[j] + p[j] / 2); } } } return *min_element(d.begin(), d.end()); } int main() { ios::sync_with_stdio(false); int T; cin >> T; while(T--) cout << solve() << endl; return 0; }