CF230 D2D:Tower of Hanoi,dp

题目:http://codeforces.com/contest/392/problem/B

之前用递归不好做,直接dp简单多了。思想与经典汉诺塔问题差不多。

代码:

// Tower of Hanoi

#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <iostream>
#include <sstream>
#include <iomanip>

#include <bitset>
#include <string>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <set>
#include <map>

#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <ctime>
#include <climits>

using namespace std;
typedef pair<int, int> pii;
typedef long long llong;
typedef pair<llong, llong> pll;
#define mkp make_pair

#define CHECKTIME() printf("%.2lf\n", (double)clock() / CLOCKS_PER_SEC)

long long dp[41][3][3];
int t[3][3];
int n;

int main()
{
#ifdef LOCAL_DEBUG
	freopen("in.txt", "r", stdin);
#endif
	
	while ( cin >> t[0][0] >> t[0][1] >> t[0][2] ) {
		cin >> t[1][0] >> t[1][1] >> t[1][2];
		cin >> t[2][0] >> t[2][1] >> t[2][2];
		cin >> n;
		memset(dp, 0, sizeof(dp));
		for (int cur = 1; cur <= n; cur++) {
			for (int p1 = 0; p1 < 3; p1++) {
				for (int p3 = 0; p3 < 3; p3++) {
					int p2 = 3 - p1 - p3;
					if (p1 == p3) {
						continue;
					}
					dp[cur][p1][p3] = min(
						dp[cur-1][p1][p2] + t[p1][p3] + dp[cur-1][p2][p3],
						dp[cur-1][p1][p3] + t[p1][p2] + dp[cur-1][p3][p1] +
						t[p2][p3] + dp[cur-1][p1][p3]
					);
				}
			}
		}
		cout << dp[n][0][2] << endl;
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值