uva 662

dp +路径输出

#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <stack>
#include <vector>
#include <sstream>
#include <cstring>
#include <string>
#include <map>
#include <set>
#include <queue>
#include <algorithm>
#include <iostream>
#define FFI freopen("in.txt", "r", stdin)
#define maxn 1010
#define INF 0x3f3f3f3f
#define inf 10000000
#define MOD 1000000007
#define ULL unsigned long long
#define LL long long
#define _setm(houge) memset(houge, INF, sizeof(houge))
#define _setf(houge) memset(houge, -1, sizeof(houge))
#define _clear(houge) memset(houge, 0, sizeof(houge))
using namespace std;

int dp[35][205], n, k;
int loc[210], w[210][210];

void fun(int m,int x,int y) {  
    if(x == y) 
        printf("Depot %d at restaurant %d serves restaurant %d\n", m, x, y);  
    else 
        printf("Depot %d at restaurant %d serves restaurants %d to %d\n", m, (x+y)/2, x, y);  
}

void print(int x, int y, int sum) {  
    if(x == 1) {
        fun(x, x, y); 
        return;
    }  
    else {  
        for(int i = x; i <= y; ++ i) {  
            if(w[i][y] + dp[x-1][i-1] == sum) {
                print(x-1, i-1, sum-w[i][y]);  
                fun(x, i, y);  
                break;  
            }  
        }  
    }  
}

int main() {
    FFI;
    int ca = 0;
    while(scanf("%d%d", &n, &k) == 2 && n+k) {
        for(int i = 1; i <= n; ++ i) {
            scanf("%d", &loc[i]);
        }
        _clear(w);
        _setm(dp);
        for(int i = 1; i <= n; ++ i) {
            for(int j = i; j <= n; ++ j) {
                for(int d = i; d <= j; ++ d) {
                    w[i][j] += abs(loc[d]-loc[(i+j)/2]);
                }
            }
        }
        for(int i = 1; i <= n; ++ i) dp[1][i] = w[1][i];
        for(int i = 2; i <= k; ++ i) {
            for(int j = n; j >= i; -- j) {
                for(int d = i-1; d <= j; ++ d) {
                    dp[i][j] = min(dp[i][j], dp[i-1][d]+w[d+1][j]);
                }
            }
        }
        printf("Chain %d\n", ++ ca);
        print(k, n, dp[k][n]);
        printf("Total distance sum = %d\n\n", dp[k][n]);
    }
    return 0;
}

  

posted @ 2014-08-01 15:15  xlc2845  阅读(154)  评论(0编辑  收藏  举报