XTU1168:Alice and Bob(二维DP)

Problem Description

Alice and Bob always love to play games, so does this time. 
It is their favorite stone-taken game. 
However, this time they does not compete but co-operate to finish this task. 
Suppose there is a stack of n stones. 
Each turn, 
Alice can only take away stones in number pow of 2, say 1, 2, 4, 8, 16, ... 
Bob can only take away stones in number pow of 3, say 1, 3, 9, 27, 81, ... 
They takes stones alternately, and lady first.
Notice in each turn, Alice/Bob have to take away at least one stone, unless the stack is empty. 
Now, the question is, what is the least number of operation for taking away all the stones.

Input

Multiple test cases. First line, there is an integer T ( 1 ≤ T ≤ 20 ), indicating the number of test cases. 
For each test case, there is a number n ( 1 ≤ n ≤ 10000 ), occupying a line, indicating the total number of the stones.

Ouput

For each test case, output a line. It is an integer number k, indicating the least number of operation in need to finish the task.

Sample Input
5
1
2
3
4
5
Sample Output
1
1
2
1
2

dp[i][0]表示取i颗石子到Alice的最小步数
dp[i][1]表示取i颗石子到Bob的最小步数
dp[i][0]=min(dp[i-2^k][1])+1) 代表 alice 取一次,后得到的 bob取得最小数量加上刚才aclice取得1次,等于alice取得最小次数
同理dp[i][1]=min(dp[i-3^k][0]+1)
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define L 10001
#define inf 1<<30
int dp[L][2];

int main()
{
    int n,t,i,j;
    dp[0][0] = dp[0][1] = 0;
    dp[1][0] = dp[1][1] = dp[2][0] = 1;
    dp[2][1] = 2;
    for(i = 3; i<L; i++)
    {
        dp[i][0] = dp[i][1] = inf;
        for(j = 1; j<=i; j*=2)
            dp[i][0] = min(dp[i][0],dp[i-j][1]+1);
        for(j = 1; j<=i; j*=3)
            dp[i][1] = min(dp[i][1],dp[i-j][0]+1);
    }
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&n);
        printf("%d\n",dp[n][0]);
    }

    return 0;
}


 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值