wiki 1258 关路灯

来源:互联网 发布:怎么买东西便宜 知乎 编辑:程序博客网 时间:2024/06/10 03:00
动态规划。
设f[i,j,0]表示第i到j个路灯关完停在左边的最小耗费,f[i,j,1]为右边
g[i,j]表示除了i到j路灯,其他路灯每秒耗费总和
f[i,j,0]=min{f[i+1,j,1]+g[i+1,j]*(dis[j]-dis[i]),f[i+1,j,0]+g[i+1,j]*(dis[i+1]-dis[i])}
f[i,j,1]=min{f[i,j-1,1]+g[i,j-1]*(dis[j]-dis[j-1]),f[i,j-1,0]+g[i,j-1]*(dis[j]-dis[i])} 
边界:f[i,j,1]=f[i,j,0]=maxlongint f[k,k,1]=f[k,k,0]=0

ans=min{f[1,n,0],f[1,n,1]}


#include<cstdio>#include<cstring>#include<iostream>#include<iomanip>#include<queue>#include<cmath>#include<stack>#include<map>#include<vector>#include<set>#include<algorithm>using namespace std;const int maxN = 1100;const int INF = 1 << 30;int n,s;int dis[maxN],cost[maxN],dp[maxN][maxN][2],shengyu[maxN][maxN];void init(){    cin >> n;    cin >> s;    int total = 0;    for(int i = 1; i <= n; i++){        cin >> dis[i] >> cost[i];        total += cost[i];    }    for(int i = 1; i <= n; i++){        for(int j = i; j <= n; j++) {            dp[i][j][0] = INF;            dp[i][j][1] = INF;        }    }    dp[s][s][0] = 0;    dp[s][s][1] = 0;    for(int i = 1; i <= n; i++){        for(int j = i; j <=n; j++){            for(int u = i; u <= j; u++){                shengyu[i][j] += cost[u];            }            shengyu[i][j] = total - shengyu[i][j];        }    }}int small (int a, int b){    return (a < b ? a : b);}int main(int argc, const char * argv[]){    init();    for(int j = s; j <= n; j++){        for(int i = j-1; i >= 1; i--){            dp[i][j][0] = small(dp[i+1][j][1]+shengyu[i+1][j]*(dis[j]-dis[i]), dp[i+1][j][0]+shengyu[i+1][j]*(dis[i+1]-dis[i]));            dp[i][j][1] = small(dp[i][j-1][1]+shengyu[i][j-1]*(dis[j]-dis[j-1]), dp[i][j-1][0]+shengyu[i][j-1]*(dis[j]-dis[i]));        }    }    cout << small(dp[1][n][0], dp[1][n][1]) << endl;}


0 0
原创粉丝点击