#include using namespace std; int t,n,i,j,k,l,a[1005],b[1005],d[1005][4],f[1005][1005][4],ans; int dis(int x,int y) { if(x>y)swap(x,y); return y-x+1>>1; } int main() { scanf("%d",&t); while(t--) { scanf("%d",&n); memset(f,127,sizeof(f)); for(i=1;i<=n;i++) { scanf("%d%d",a+i,b+i); d[i][0]=a[i]; d[i][1]=b[i]; d[i][2]=min(b[i],a[i]+1); d[i][3]=max(a[i],b[i]-1); for(j=0;j<4;j++)f[0][i][j]=0; } for(i=0;i=a[i+1]&&d[j][k]<=b[i+1])f[i+1][j][k]=min(f[i+1][j][k],f[i][j][k]); else for(l=0;l<4;l++)f[i+1][i+1][l]=min(f[i+1][i+1][l],f[i][j][k]+dis(d[i+1][l],d[j][k])); for(ans=f[0][0][0],i=1;i<=n;i++)for(j=0;j<4;j++)ans=min(ans,f[n][i][j]); cout<