HDU 1227(Fast Food)

动态规划题,状态转移方程为 dp[i][j] = min(dp[i-1][k] + cost[k+1][j]),其中 dp[i][j] 表示前 j 个餐厅建 i 个仓库的最短距离和,cost[i][j] 表示在第 i 个餐厅到第 j 个餐厅之间建一个仓库的最短距离和,可知该仓库建立在下标为 (i+j)/2 的餐厅处。

#include <iostream>
#include <cstring>
#include <cmath>
#include <algorithm>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 205;

int pos[MAXN]; //餐厅的位置
int dp[35][MAXN]; //动态规划数组
int cost[MAXN][MAXN]; //建立一个仓库的最小总距离

int main()
{
    int n, m; //餐厅数,仓库数
    int test = 1; //测试用例数
    while (cin >> n >> m)
    {
        if (n == 0 && m == 0)
            break;

        for (int i = 1; i <= n; i++)
        {
            cin >> pos[i];
        }

        memset(cost, 0, sizeof(cost));
        memset(dp, 0, sizeof(dp));

        for (int i = 1; i < n; i++) //计算cost数组
        {
            for (int j = i + 1; j <= n; j++)
                for (int k = i; k <= j; k++)
                    cost[i][j] += abs(pos[k] - pos[(i + j) / 2]);
        }

        for (int i = 1; i <= n; i++)
        {
            dp[1][i] = cost[1][i];
        }

        for (int i = 2; i <= m; i++) //动态规划
        {
            for (int j = i + 1; j <= n; j++)
            {
                dp[i][j] = INF;
                for (int k = i - 1; k < j; k++)
                    dp[i][j] = min(dp[i][j], dp[i - 1][k] + cost[k + 1][j]);
            }
        }
        
        cout << "Chain " << test++ << endl;
        cout << "Total distance sum = " << dp[m][n] << endl << endl;
    }
    return 0;
}
发布了152 篇原创文章 · 获赞 1 · 访问量 7621

猜你喜欢

转载自blog.csdn.net/Intelligence1028/article/details/104689214
今日推荐