Edge Game
题面
Cuber QQ know an Edge Game, in which two players move their tokens on edges alternatively. Specifically, the game starts with a fixed and given undirected tree. Player A and Player B each has a token on one node. They move in turn. In each step, the player moves his/her own token to a node adjacent to the current node located. Player A moves first. The player who first moves his/her token on the other's wins. Determine if A can win if each plays optimally.
Input
In the first line there is one integer \(n(2≤n≤10^5)\), representing the number of nodes in the tree.
In each of the next \(n−1\) lines are two integers \(u,v(1≤u,v≤n,u≠v)\) each, representing there is an edge between node \(u\) and node \(v\).
In the last line are two integers \(a,b(1≤a,b≤n,a≠b)\), representing the node A's token and B's token is on initially.
Output
One line "Yes" or "No", denoting the winner.
Examples
Input
3
1 2
1 3
1 3
Output
Yes
Input
3
1 2
1 3
2 3
Output
No
题目分析
题意:
给你一个无向图,玩家A和玩家B在一个节点上各有一个令牌。它们依次移动自己的令牌,并能做出最佳的选择。在每个步骤中,玩家将自己的令牌移动到与当前节点相邻的节点。玩家A先移动。第一个将自己的令牌移动到对方令牌的位置上的玩家获胜。
这是一道简单的单源最短路问题,直接求出A初始节点到B初始节点的最短路距离,如果距离为奇数,那么A必赢,反之B赢。
这里给出的是SPFA的做法:
AC 代码
#include <bits/stdc++.h>
#define io ios::sync_with_stdio(false);cin.tie(0);cout.tie(0)
#define rT printf("\nTime used = %.3lf\n", (double)clock()/CLOCKS_PER_SEC)
using namespace std;
const int N = 2e5 + 100;
typedef pair<int, int> PII;
int h[N], e[N], ne[N], idx;
int dist[N], n;
bool st[N];
inline void add(int a, int b) {
e[idx] = b; ne[idx] = h[a]; h[a] = idx ++;
}
int spfa(int x, int y) {
memset(dist, 0x3f, sizeof dist);
dist[x] = 0; st[x] = 1;
queue<int> q; q.push(x);
while(q.size()) {
int t = q.front(); q.pop();
st[t] = 0;
for(int i = h[t]; i != -1; i = ne[i]) {
int j = e[i];
if(dist[j] > dist[t] + 1) {
dist[j] = dist[t] + 1;
if(!st[j]) {
q.push(j);
st[j] = 1;
}
}
}
}
return dist[y];
}
int main() {
int x, y;
memset(h, -1, sizeof h);
scanf("%d", &n);
for (int i = 1; i < n; i++) {
int a, b; scanf("%d%d", &a, &b);
add(a, b); add(b, a);
}
scanf("%d%d", &x, &y);
int t = spfa(x, y);
if(t & 1) puts("Yes");
else puts("No");
return 0;
}