nyoj 740 “炫舞家“ST

本文详细解析了一道来自ACM竞赛的动态规划与图论相结合的问题,通过实例展示了如何利用动态规划解决复杂路径选择问题,并提供了完整的代码实现和解题思路。

题目来源:http://acm.nyist.net/JudgeOnline/problem.php?pid=740

参考算法艺术与信息学竞赛http://download.csdn.net/detail/hearthougan/5907359第118页。这里就不再赘述了。

 

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>

using namespace std;

const int MAXN = 10010;

int cost[6][6];
void Inite()
{
    int i, j;
    for(i = 0; i < 6; ++i)
        for(j = 0; j < 6; ++j)
            cost[i][j] = MAXN;
    for(i = 0; i < 5; ++i)
    {
        cost[i][i] = 1;
        if(i != 0)
            cost[0][i] = 2;
    }
    cost[1][2] = cost[2][1] = cost[2][3] = cost[3][2] = cost[3][4] = cost[4][3] = cost[1][4] = cost[4][1] = 3;
    cost[1][3] = cost[3][1] = cost[2][4] = cost[4][2] = 4;
}

int main()
{
    int dp[5][5][MAXN], a[MAXN];
    int i, j, k, n;
    Inite();
    while(scanf("%d", &a[0]))
    {
        if(!a[0])
            break;
        n = 1;
        while(1)
        {
            scanf("%d", &a[n++]);
            if(a[n-1] == 0)
                break;
        }
        memset(dp, 0, sizeof(dp));
        for(k = n-2; k >= 0; --k)
            for(i = 0; i < 5; ++i)
                for(j = 0; j < 5; ++j)
                    dp[i][j][k] = min(dp[i][a[k]][k+1] + cost[j][a[k]], dp[a[k]][j][k+1] + cost[i][a[k]]);
        printf("%d\n", dp[0][0][0]);
    }
    return 0;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值