您的位置:首页 > 其它

历届试题 约数倍数选卡片

2017-03-02 08:00 381 查看
思路:直接dfs搜索各种后继状态,抓住博弈的性质:对于必胜状态,必有一个后继状态是必败的,对于必败状态所有后继状态都是必胜的。假设当前选择是必胜态,那么后手的所有选择都必须是P态才行。

AC代码: 562ms

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <utility>
#include <string>
#include <iostream>
#include <map>
#include <set>
#include <vector>
#include <queue>
#include <stack>
using namespace std;
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define eps 1e-10
#define inf 0x3f3f3f3f
#define PI pair<int, int>
typedef long long LL;
const int maxn = 100 + 5;
vector<int>choice[maxn], a;
int cnt[maxn];

char in(int &a) {
char ch;
while((ch=getchar()) < '0' || ch > '9');
for(a = 0; ch >= '0' && ch <= '9'; ch=getchar()) {
a = a *10 + ch - '0';
}
return ch;
}
bool dfs(int x) {
int flag = 0;
for(int i = choice[x].size()-1; i >= 0; --i) {
int y = choice[x][i];
if(cnt[y] > 0) {
flag = 1;
cnt[y]--;
bool ok = dfs(y);
cnt[y]++;
if(ok) return false; //后手能取得N态,那么当前是P态
}
}
if(!flag) return true; //已经无法再取卡片
return true;  //当前所有可能情况都是P态
}

void init() {
for(int i = 1; i <= 100; ++i){
if(!cnt[i]) continue;
for(int j = 1; j <= 100; ++j) {
if(!cnt[j]) continue;
if(i % j == 0) choice[i].push_back(j); //约数
else if(j % i == 0 && i != j) choice[i].push_back(j);  //倍数
}
}
}
int main() {
memset(cnt, 0, sizeof(cnt));
int n, x;
char ch = 'x';
for(int i = 0; ch != '\n'; ++i) {
ch = in(x);
cnt[x]++;
if(ch == '\n') continue;

}
init();
ch = 'x';
for(n = 0; ch != '\n'; ++n) {
ch = in(x);
a.push_back(x);
}
int flag = 0;
for(int i = 0; i < n; ++i) {
cnt[a[i]]--;
if(dfs(a[i])) { //假设当前状态是必胜状态
flag = 1;
printf("%d\n", a[i]);
break;
}
cnt[a[i]]++;
}

if(!flag) printf("-1\n");
return 0;
}


如有不当之处欢迎指出!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: