poj1485 Fast Food 动态规划

 
//poj 1485
//fenix_bao
#include <iostream>

using namespace std;
const int MAXN=256,MAXK=32;
int pos[MAXN],dp[MAXN][MAXK],dis[MAXN][MAXN],one_cover[MAXN][MAXN];
int sum_dis[MAXN][MAXN],sum_dis_rev[MAXN][MAXN];
int one_cover_mark[MAXN][MAXN];
int dp_mark[MAXN][MAXK];

void myprint(int n,int k){
    if(k==0){
        return;
    }
    int pre_n = dp_mark[n][k];
    int pre_k = k-1;
    myprint(pre_n,pre_k);
    int from = pre_n+1;
    int to = n;
    if(from!=to){
        printf("Depot %d at restaurant %d serves restaurants %d to %d\n",k,one_cover_mark[from][to],from,to);
    }else{
        printf("Depot %d at restaurant %d serves restaurant %d\n",k,from,from);
    }
}


int main() {
    int n,k,case_cnt=0;
    while(scanf("%d%d",&n,&k)==2&&(n||k)){
        for(int i=1;i<=n;++i)
            scanf("%d",&pos[i]);

        for(int i=1;i<=n;++i)
            for(int j=i;j<=n;++j)
                dis[i][j]=dis[j][i]=pos[j]-pos[i];

        for(int i=1;i<=n;++i) {
            sum_dis[i][i]=0;
            for (int j = i-1; j >= 1; --j) {
                sum_dis[j][i] = sum_dis[j+1][i]+dis[j][i];
            }
            sum_dis_rev[i][i]=0;
            for (int j = i+1; j<=n; ++j) {
                sum_dis_rev[i][j] = sum_dis_rev[i][j-1]+dis[i][j];
            }
        }

        for(int i=1;i<=n;++i)
            for(int j=1;j<=n;++j)
                one_cover[i][j]=INT_MAX,dp[i][j]=INT_MAX;

        for(int i=1;i<=n;++i)
            for(int j=i;j<=n;++j)
                for(int p=i;p<=j;++p){
                    if(sum_dis[i][p]+sum_dis_rev[p][j]<=one_cover[i][j]){
                        one_cover[i][j] = sum_dis[i][p]+sum_dis_rev[p][j];
                        one_cover_mark[i][j] = p;
                    }
                }

        dp[0][0]=0;
        for(int i=1;i<=n;++i)
            for(int p=1;p<=i&&p<=k;++p)
                for(int j=p-1;j<i;++j) {
                    if (!(j != 0 && p - 1 == 0)) {
                        if(dp[j][p - 1] + one_cover[j + 1][i]<dp[i][p]){
                            dp[i][p] = dp[j][p - 1] + one_cover[j + 1][i];
                            dp_mark[i][p] = j;
                        }
                    }
                }

        printf("Chain %d\n",++case_cnt);
        myprint(n,k);
        printf("Total distance sum = %d\n\n",dp[n][k]);
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值