POJ 2599 A funny game#树形SG(DFS实现)

时间:2022-05-09 06:14:54

http://poj.org/problem?id=2599

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<vector>
using namespace std; int n,k,pos;
vector<int> g[1005];
bool flag[1005]; int dfs(int k)
{
for(int i=0;i<g[k].size();i++)
{
int t=g[k][i];
if(!flag[t])
{
flag[t]=1;
if(!dfs(t))
{
pos=t;
return 1;//k状态为败,则i状态为胜
}
flag[t]=0;//初始化,进行下一次遍历
}
}
return 0;
} int main()
{
int n,k;
while(~scanf("%d%d",&n,&k))
{
for(int i=1;i<=n;i++)
g[i].clear();
for(int i=1;i<n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
memset(flag,0,sizeof(flag));
flag[k]=1;
if(dfs(k)) printf("First player wins flying to airport %d\n",pos);
else printf("First player loses\n");
}
return 0;
}