timus 1180. Stone Game 解题报告

1.题目:

1180. Stone Game

Time limit: 1.0 second
Memory limit: 64 MB
Two Nikifors play a funny game. There is a heap of  N stones in front of them. Both Nikifors in turns take some stones from the heap. One may take any number of stones with the only condition that this number is a nonnegative integer power of 2 (e.g. 1, 2, 4, 8 etc.). Nikifor who takes the last stone wins. You are to write a program that determines winner assuming each Nikifor does its best.

Input

An input contains the only positive integer number  N (condition  N ≤ 10^250 holds).

Output

The first line should contain 1 in the case the first Nikifor wins and 2 in case the second one does. If the first Nikifor wins the second line should contain the minimal number of stones he should take at the first move in order to guarantee his victory.

Sample

inputoutput
8
1
2

 

2.解题思路

这种博弈问题,都是从最简单的情况考虑,递推到复杂情况的。但是这道题有一些有趣的技巧~

基本的递推:

N  win?

1  y

2  y

3  n

嗯。分析到这里,思路大概是这样的:

bool suc[maxN+1];

suc[1] = suc[2] = true;

for (i = 3; i <= n; i++) {

  for (b = 1; b < n; b *= 2) {

    if (suc[i-b] == false) {

      suc[i] = true;

      break;

    }

  }

}

然而再回头看一下题目规模,发现n的取值范围是n <= 10^250。这是要高精度的节奏啊。

不急,回去再看一下有没有优化的方法。通过找规律,

发现:N = 3*n, suc[n] = n

   N = 3*n + 1 || N = 3*n + 2, suc[n] = y

这样问题转换为求n%3。

而一个十进制数N = sum(ai*10^i) = sum(ai) + sum(ai*(10^i-1))(i>=0)

而10^i-1 = 0 (mod3)

故N = sum(ai) (mod3)

3.代码:

#include <iostream>
using namespace std;
int main()
{
    int s = 0;
    char tmp;
    while (cin >> tmp) s += tmp - '0';
    if (s % 3 == 0) cout << 2;
    else cout << 1 << '\n' << s % 3;
    //return 0;
}

 

转载于:https://www.cnblogs.com/IVY-BUG/p/5245289.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值