#include #include #include #include #include int T,n; int a[1050],b[1050]; int LL,RR,spos; long long ans; long long x1,x2; int p1,p2; inline int dist(int x,int y){return (std::abs(x-y)+1)/2;} int main(){ scanf("%d",&T); while (T--){ scanf("%d",&n); for (int i=1;i<=n;i++) scanf("%d%d",&a[i],&b[i]); ans=x1=x2=p1=p2=0; LL=1,RR=1000000,spos=1; while (spos<=n&&std::max(a[spos],LL)<=std::min(b[spos],RR)) LL=std::max(LL,a[spos]),RR=std::min(RR,b[spos]),spos++; // printf("LL=%d RR=%d\n",LL,RR); a[spos-1]=LL,b[spos-1]=RR; if (spos>n){puts("0");continue;} if (a[spos]>RR) p1=p2=RR; else p1=p2=LL; // printf("pos=%d\n",p1); for (int i=spos;i<=n;i++){ long long nxt1=0x3f3f3f3f3f3f3f3f,nxt2=0x3f3f3f3f3f3f3f3f; int np1=0,np2=0; if ((a[i]<=p1&&p1<=b[i])||(a[i]<=p2&&p2<=b[i])) continue; if (a[i]==b[i]) nxt1=nxt2=std::min(dist(p1,a[i])+x1,dist(p2,a[i])+x2),np1=np2=a[i]; else{ if (a[i]>p1||a[i]>p2) np1=a[i],np2=a[i]+1; else np1=b[i]-1,np2=b[i]; nxt1=std::min(nxt1,dist(p1,np1)+x1); nxt1=std::min(nxt1,dist(p2,np1)+x2); nxt2=std::min(nxt2,dist(p1,np2)+x1); nxt2=std::min(nxt2,dist(p2,np2)+x2); } x1=nxt1,x2=nxt2,p1=np1,p2=np2; } printf("%I64d\n",std::min(x1,x2)); } }