历届试题 约数倍数选卡片

         思路:直接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;
}

如有不当之处欢迎指出!

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值