双塔DP。
#include<cstdio>
#include<cstring>
#include<queue>
#include<string>
#include<algorithm>
#include<map>
#include<iostream>
using namespace std; const int maxn=+;
int T,n;
int dp[maxn][*maxn];
int a[maxn],b[maxn]; void init()
{
for(int i=;i<=n;i++)
for(int j=;j<=;j++)
dp[i][j]=0x7fffffff;
} void read()
{
scanf("%d",&n);
for(int i=;i<=n;i++) scanf("%d%d",&a[i],&b[i]);
} void work()
{
dp[][a[]+]=dp[][-b[]+]=; for(int i=;i<=n;i++)
{
for(int j=;j<=;j++)
{
if(dp[i-][j]==0x7fffffff) continue;
int tmp=j-;
if(tmp>=)
{
dp[i][a[i]+]=min(dp[i][a[i]+],dp[i-][j]+tmp);
if(b[i]>=tmp) dp[i][tmp-b[i]+]=min(dp[i][tmp-b[i]+],dp[i-][j]+tmp);
else if(b[i]<tmp) dp[i][tmp-b[i]+]=min(dp[i][tmp-b[i]+],dp[i-][j]+b[i]);
} else if(tmp<)
{
tmp=-tmp;
if(dp[i-][j]+tmp<dp[i][-b[i]+]) dp[i][-b[i]+]=min(dp[i][-b[i]+],dp[i-][j]+tmp);
if(a[i]<=tmp) dp[i][a[i]-tmp+]=min(dp[i][a[i]-tmp+],dp[i-][j]+a[i]);
else if(a[i]>tmp) dp[i][a[i]-tmp+]=min(dp[i][a[i]-tmp+],dp[i-][j]+tmp);
}
}
} int ans=0x7fffffff;
for(int j=;j<=;j++)
{
if(dp[n][j]==0x7fffffff) continue;
ans=min(ans,dp[n][j]+abs(j-));
}
printf("%d\n",ans);
} int main()
{
scanf("%d",&T);
while(T--)
{
read();
init();
work();
}
return ;
}