poj 1485 Fast Food dp

題意:給定n個在一條直線上的快餐店,在這n個點處,可建k個倉庫,每個快餐店去最近的倉庫取貨,問走的路程和最小是多少,並輸出每個店的位置及供給區間

 

狀態轉移方程:

dp[i][j] = dp[k][j-1] + cost[k+1][i]

dp[i][j]表示前i個點,簡歷j個倉庫,路程和

 

每個倉庫建的地點爲區間[i, j]的中間,即( i + j) /2

 

dfs輸出路徑

 

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
int p[210], ans[210], n, m, dp[210][35], cost[210][210];
struct node{
    int x, y;
}path[210][35];
void dynamic(){
    int i, j, k;
    memset( dp, 0x3f, sizeof( dp));
    for( i= 0; i<= n; i++)
        dp[i][1] = cost[1][i];
    for( i= 1; i<= n; i++){
        for( j= 2; j<= m; j++){
            for( k= 1; k<i; k++){
                if( dp[i][j] >= dp[k][j-1] + cost[k+1][i]){
                    dp[i][j] = dp[k][j-1] + cost[k+1][i];
                    path[i][j].x = k;
                    path[i][j].y = j-1;
                }
            }
        }
    }
}
void print(int ans, int t){
    node head = path[ans][t];
    node next = path[head.x][head.y];
    if( t > 1) print(head.x, head.y);
    if( ans - head.x == 1)
    printf("Depot %d at restaurant %d serves restaurant %d\n", t, ans, ans);
    else
    printf("Depot %d at restaurant %d serves restaurants %d to %d\n", t, (head.x + ans + 1)/2, head.x+1, ans);
}
int main(){
	//freopen("1.txt", "r", stdin);
	int i, j, k, tmp, tt, mm, cas = 1, mem[40];
    while( scanf("%d%d", &n, &m) && !( n== 0 && m== 0)){
        for( i= 1; i<= n; i++){
            scanf("%d", &p[i]);
        }
        for( i= 1; i<= n; i++){
            for( j= 1; j<= n; j++){
                tt = (i+j)/2;
                tmp = 0;
                for( k= i; k< tt; k++){
                    tmp += (p[tt] - p[k]);
                }
                for( k= tt+1; k<= j; k++){
                    tmp += (p[k] - p[tt]);
                }
                cost[i][j] = tmp;
            }
        }
        dynamic();
        printf("Chain %d\n", cas++);
        print(n, m);
        printf("Total distance sum = %d\n\n", dp[n][m]);
    }
	return 0;
}


 

發佈了69 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章