解题思路:这道题很明显是用区间dp,可是与以往的区间dp不同,因为对于区间[i,j],机器人所处的位置要么在i,要么在j(因为机器人要移动到某一点才能关闭灯泡,所以对于某一段区间来说,机器人最后肯定在两个端点上,否则将不能成立),那么既然要表示在左端点还是右端点,所以我们再开三维数组dp[i][j][0]表示停留在i点,dp[i][j][1]表示停留在j点,那么剩下的就是状态方程了,跟普通的区间dp一样,很容易写出来。。具体的看代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn = 1005;
int n,v,sum[maxn];
int dp[maxn][maxn][2],cost[maxn],dis[maxn];
void solve()
{
memset(dp,0x1f,sizeof(dp));
dp[v][v][0] = dp[v][v][1] = 0;
for(int l = 2; l <= n; l++)
{
for(int i = 1; i <= n; i++)
{
int j = i + l - 1;
if(j > n) break;
dp[i][j][0] = min(dp[i][j][0],dp[i+1][j][0] + (sum[n]-sum[j]+sum[i])*(dis[i+1]-dis[i]));
dp[i][j][0] = min(dp[i][j][0],dp[i+1][j][1] + (sum[n]-sum[j]+sum[i])*(dis[j]-dis[i]));
dp[i][j][1] = min(dp[i][j][1],dp[i][j-1][0] + (sum[n]-sum[j-1]+sum[i-1])*(dis[j]-dis[i]));
dp[i][j][1] = min(dp[i][j][1],dp[i][j-1][1] + (sum[n]-sum[j-1]+sum[i-1])*(dis[j]-dis[j-1]));
}
}
printf("%d\n",min(dp[1][n][0],dp[1][n][1]));
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
scanf("%d",&v);
for(int i = 1; i <= n; i++)
scanf("%d%d",&dis[i],&cost[i]);
sum[0] = 0;
for(int i = 1; i <= n; i++)
sum[i] = sum[i-1] + cost[i];
solve();
}
return 0;
}