题目链接:http://acm.hust.edu.cn/vjudge/problem/51193
题意:直线上有n个点,每个点有一个坐标xi和时间di,此点会在di时间时消失。现在可以从任意点出发,问在点消失前访问所有的点的最短时间。
思路:dp[i][j][k]表示已经访问完区间[i,j]内的点,而且此时在区间左端点/右端点的最短时间。那么[i][j][0]由[i+1][j][0/1]转移而来,[i][j][1]由[i][j-1][0/1]转移而来。
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <sstream>
#include <queue>
#include <utility>
using namespace std;
#define rep(i,j,k) for (int i=j;i<=k;i++)
#define Rrep(i,j,k) for (int i=j;i>=k;i--)
#define Clean(x,y) memset(x,y,sizeof(x))
#define LL long long
#define ULL unsigned long long
#define inf 0x7fffffff
#define mod 100000007
const int maxn = 10002;
int n;
int pos[maxn];
int deadline[maxn];
LL dp[maxn][maxn][2];
int cost( int a , int b )
{
return abs( a - b );
}
void init()
{
Clean(dp,0x3f);
rep(i,1,n)
{
scanf("%d %d",&pos[i],&deadline[i]);
if ( deadline[i] > 0 ) dp[i][i][0] = dp[i][i][1] = 0;
}
}
void solve()
{
rep(L,2,n)
rep(i,1,n-L+1)
{
int j = i + L - 1;
int c;
c = cost( pos[i] , pos[i+1] );
if ( dp[i+1][j][0] + c < deadline[i] )
dp[i][j][0] = min( dp[i][j][0] , dp[i+1][j][0] + c );
c = cost( pos[j-1] , pos[j] );
if ( dp[i][j-1][1] + c < deadline[j] )
dp[i][j][1] = min( dp[i][j][1] , dp[i][j-1][1] + c );
c = cost( pos[i] , pos[j] );
if ( dp[i+1][j][1] + c < deadline[i] )
dp[i][j][0] = min( dp[i][j][0] , dp[i+1][j][1] + c );
if ( dp[i][j-1][0] + c < deadline[j] )
dp[i][j][1] = min( dp[i][j][1] , dp[i][j-1][0] + c );
}
LL ans = min( dp[1][n][0] , dp[1][n][1] );
if ( ans >= (LL)4557430888798830300 )
puts("No solution");
else printf("%lld\n",ans);
}
int main()
{
while( scanf("%d",&n) == 1 )
{
init();
solve();
}
return 0;
}