首页 > 其他 > 详细

codechef - Bytelandian gold coins 题解

时间:2014-06-02 23:02:48      阅读:533      评论:0      收藏:0      [点我收藏+]

In Byteland they have a very strange monetary system.

Each Bytelandian gold coin has an integer number written on it. A coin n
can be exchanged in a bank into three coins: n/2, n/3 and n/4.
But these numbers are all rounded down (the banks have to make a profit).

You can also sell Bytelandian coins for American dollars. The exchange
rate is 1:1. But you can not buy Bytelandian coins.

You have one gold coin. What is the maximum amount of American dollars
you can get for it?

Input

The input will contain several test cases (not more than 10). Each
testcase is a single line with a number n, 0 <= n <= 1 000 000 000.
It is the number written on your coin.

Output

For each test case output a single line, containing the maximum amount
of American dollars you can make.

Example

Input:
12
2

Output:
13
2

本题使用动态规划法, 或者记忆法,加上递归法。
不加上递归法,好像很麻烦,因为我们不知道其初始值,只知道其最终值,所以只能往下递推了,这样使用记忆法就比动态规划要方便了。
使用二维表设计其递归记忆表,防止重复计算。还是十分困难的,动态规划法有时候不一定比记忆法要好。
递归记忆法的学名: top-down with memoization; Introduction to Algorithm的Dynamic programming 这章有介绍

#include <stdio.h>
#include <vector>
#include <cmath>
using namespace std;

class Bytelandiangoldcoins
{
        long long calMax(vector<vector<long long> > &tbl, int n, int r, int c)
	{
		if (n < 12) return n;
		if (tbl[r][c] == 0)
		{
			tbl[r][c] = calMax(tbl, n>>1, r+1, c) + calMax(tbl, n>>2, r+2, c)
				+ calMax(tbl, n/3, r, c+1);
		}
		return tbl[r][c];
	}
public:
	Bytelandiangoldcoins()
	{
		int r = (int)ceil(log(1E9)/log(2.0));
		int c = (int)ceil(log(1E9)/log(3.0));
		int n;
		while (scanf("%d", &n) != EOF)
		{
			vector<vector<long long> > tbl(r, vector<long long>(c, 0));
			printf("%lld\n", calMax(tbl, n, 0, 0));
		}
	}
};




codechef - Bytelandian gold coins 题解,布布扣,bubuko.com

codechef - Bytelandian gold coins 题解

原文:http://blog.csdn.net/kenden23/article/details/27674907

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!