51nod1185 威佐夫游戏 V2【博弈论】

有2堆石子。A B两个人轮流拿,A先拿。每次可以从一堆中取任意个或从2堆中取相同数量的石子,但不可不取。拿到最后1颗石子的人获胜。假设A B都非常聪明,拿石子的过程中不会出现失误。给出2堆石子的数量,问最后谁能赢得比赛。

例如:2堆石子分别为3颗和5颗。那么不论A怎样拿,B都有对应的方法拿到最后1颗。

Input

第1行:一个数T,表示后面用作输入测试的数的数量。(1 <= T <= 10000)
第2 - T + 1行:每行2个数分别是2堆石子的数量,中间用空格分隔。(1 <= N <= 10^18)

Output

共T行,如果A获胜输出A,如果B获胜输出B。

Input示例

3
3 5
3 4
1 9

Output示例

B
A
A

思路:此题数据较大,如果用常规的来写的话肯定是要wa的,因为会丢失精度,第一遍wa了上网才知道要考虑高精度,给个传送门威佐夫博弈

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
#include<vector>
#include<set>
#include<map>
#include<queue>
#include<cmath>
using namespace std;
long long a[4] = {0, 618033988, 749894848, 204586834};//黄金分割数的小数点后27位保存起来
int main()
{
    int t;
    long long mod = 1e9;
    long long n, m, sum, k, fir, sec;
    scanf("%d",&t);
    while(t --)
    {
        scanf("%lld%lld",&n,&m);
        if(n > m) swap(n, m);
        k = m - n;
        fir = k / mod;//m-n的前九位
        sec = k % mod;//m-n的后九位
        sum = sec * a[3];//模拟乘法过程
        sum = fir * a[3] + sec * a[2] + sum / mod;
        sum = fir * a[2] + sec * a[1] + sum / mod;
        sum = fir * a[1] + sum / mod;
        sum += k;//因为乘的是黄金分割数,所以少加了一个自身,最后再加上
        if(sum == n) printf("B\n");
        else printf("A\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41785863/article/details/82868889