码迷,mamicode.com
首页 > 其他好文 > 详细

codechef - Bytelandian gold coins 题解

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

标签:c   style   class   blog   code   a   

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 题解

标签:c   style   class   blog   code   a   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!