取(m堆)石子遊戲
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 4610 Accepted Submission(s): 2775
Problem Description
m堆石子,兩人輪流取.隻能在1堆中取.取完者勝.先取者負輸出No.先取者勝輸出Yes,然後輸出怎樣取子.例如5堆 5,7,8,9,10先取者勝,先取者第1次取時可以從有8個的那一堆取走7個剩下1個,也可以從有9個的中那一堆取走9個剩下0個,也可以從有10個的中那一堆取走7個剩下3個.
Input
輸入有多組.每組第1行是m,m<=200000. 後面m個非零正整數.m=0退出.
Output
先取者負輸出No.先取者勝輸出Yes,然後輸出先取者第1次取子的所有方法.如果從有a個石子的堆中取若幹個後剩下b個後會勝就輸出a b.參看Sample Output.
Sample Input
2
45 45
3
3 6 9
5
5 7 8 9 10
0
Sample Output
No
Yes
9 5
Yes
8 1
9 0
10 3
思路
可以看出這是典型的Nim博弈
對于先手必敗的情況,直接輸出No就行了
對于先手必勝,我們需要讓先手第一次取走後剩下的石子保證奇異局勢為0(即後手拿的時候必敗)的狀态。
輸出的時候,讓原本的奇異局勢與目前堆的石子數異或,如果異或結果小于等于目前石子數,輸出即可
AC代碼
/*
* @Author: WZY
* @School: HPU
* @Date: 2019-01-03 16:54:58
* @Last Modified by: WZY
* @Last Modified time: 2019-01-03 17:21:29
*/
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <math.h>
#include <limits.h>
#include <map>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <string>
#include <time.h>
#define ll long long
#define ull unsigned long long
#define ms(a,b) memset(a,b,sizeof(a))
#define pi acos(-1.0)
#define INF 0x7f7f7f7f
#define lson o<<1
#define rson o<<1|1
#define bug cout<<"---------"<<endl
#define debug(...) cerr<<"["<<#__VA_ARGS__":"<<(__VA_ARGS__)<<"]"<<"\n"
const double E=exp(1);
const int maxn=1e6+10;
const int mod=1e9+7;
using namespace std;
int a[maxn];
int main(int argc, char const *argv[])
{
ios::sync_with_stdio(false);
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
freopen("out.txt", "w", stdout);
double _begin_time = clock();
#endif
int n;
while(cin>>n&&n)
{
int ans=0;
for(int i=0;i<n;i++)
{
cin>>a[i];
ans^=a[i];
}
if(!ans)
cout<<"No"<<endl;
else
{
cout<<"Yes"<<endl;
for(int i=0;i<n;i++)
{
if((ans^a[i])<=a[i])
cout<<a[i]<<" "<<(ans^a[i])<<endl;
}
}
}
#ifndef ONLINE_JUDGE
double _end_time = clock();
printf("time = %lf ms.", _end_time - _begin_time);
#endif
return 0;
}