UPC6581: Fennec VS. Snuke(dfs)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sxh759151483/article/details/81326236

Fennec and Snuke are playing a board game.
On the board, there are N cells numbered 1 through N, and N−1 roads, each connecting two cells. Cell ai is adjacent to Cell bi through the i-th road. Every cell can be reached from every other cell by repeatedly traveling to an adjacent cell. In terms of graph theory, the graph formed by the cells and the roads is a tree.
Initially, Cell 1 is painted black, and Cell N is painted white. The other cells are not yet colored. Fennec (who goes first) and Snuke (who goes second) alternately paint an uncolored cell. More specifically, each player performs the following action in her/his turn:
Fennec: selects an uncolored cell that is adjacent to a black cell, and paints it black.
Snuke: selects an uncolored cell that is adjacent to a white cell, and paints it white.
A player loses when she/he cannot paint a cell. Determine the winner of the game when Fennec and Snuke play optimally.

Constraints
2≤N≤105
1≤ai,bi≤N
The given graph is a tree.

输入

Input is given from Standard Input in the following format:
N
a1 b1
:
aN−1 bN−1

输出

If Fennec wins, print Fennec; if Snuke wins, print Snuke.

样例输入

7
3 6
1 2
3 1
7 4
5 7
1 4

样例输出

Fennec

提示

For example, if Fennec first paints Cell 2 black, she will win regardless of Snuke's moves.

来源/分类

ABC067&ARC078 

F和S玩涂色游戏,有一个树初始结点1是黑色的,结点n是白色的。F先开始选择与黑色相邻的一个空白结点涂成黑色,S选择一个与白色相邻的结点涂成白色,最后谁没有空白结点涂的时候谁就输。

先确定1到n的距离,将这条路线先涂完分成黑色和白色,然后找出与黑色相邻结点的个数,和与白色相邻结点的个数,比较大小如果黑色>白色则F赢,否则S赢。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 5;
vector<int> V[maxn];
int u, v, n, vis[maxn], vis1[maxn], vis2[maxn], color[maxn];
int flag = 0, ans1 = 0, ans2 = 0;
void dfs(int p, int deep){
	if(p == n){
		flag = deep;
		return ;
	}
	for(int i = 0; i < V[p].size(); i++){
		if(!vis[V[p][i]]){
			vis[V[p][i]] = 1;
			dfs(V[p][i], deep + 1);
		}
		if(flag){
			if(deep <= flag / 2) color[p] = 1;
			else if(deep > flag / 2) color[p] = -1;
			return ;
		}
	}
}

void DFS1(int p){
	if(color[p] != -1){
		ans1++;
		for(int i = 0; i < V[p].size(); i++){
			if(!vis[V[p][i]]){
				vis[V[p][i]] = 1;
				DFS1(V[p][i]);
			}
		}
	}
}

void DFS2(int p){
	if(color[p] != 1){
		ans2++;
		for(int i = 0; i < V[p].size(); i++){
			if(!vis[V[p][i]]){
				vis[V[p][i]] = 1;
				DFS2(V[p][i]);
			}
		}
	}
}

int main()
{
	scanf("%d", &n);
	for(int i = 1; i < n; i++){
		scanf("%d%d", &u, &v);
		V[u].push_back(v);
		V[v].push_back(u);
	}
	color[1] = 1;
	color[n] = -1;
	
	memset(vis, 0, sizeof(vis));
	vis[1] = 1;
	dfs(1, 0);
	
	memset(vis, 0, sizeof(vis));
	vis[1] = 1;
	DFS1(1);
	
	memset(vis, 0, sizeof(vis));
	vis[n] = 1;
	DFS2(n);
	
	if(ans1 - ans2 > 0)
		printf("Fennec\n");
	else
		printf("Snuke\n");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sxh759151483/article/details/81326236