O(n^2)TSP:
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
#define INF 0x3f3f3f3f
int n,d[],dp[][];
int dis(int a,int b)
{
int tmp=abs(d[a]-d[b]);
return min(tmp,-tmp);
}
int TSP_Dp()
{
dp[][]=dis(,);
for (int i = ; i <= n + ; i++) {
dp[i][i-] = INF; for (int j = ; j < i-; j++) {
dp[i][i-] = min(dp[i][i-], dp[i-][j] + dis(i, j));
dp[i][j] = dp[i-][j] + dis(i, i-);
}
} int ans = INF;
for (int i = ; i <= n; i++)
ans = min(ans, dp[n+][i] + dis(n+, i));
return ans;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
d[]=;
int ans=;
scanf("%d",&n);
for(int i=;i<=n+;i++)
{
int a;
scanf("%d%d",&a,&d[i]);
if(i==n+)ans+=a*;
ans+=;
}
ans+=TSP_Dp();
printf("%d\n",ans);
}
}