Game on a Tree
Alice and Bob play a game on a tree. Initially, all nodes are white.
Alice is the first to move. She chooses any node and put a chip on it. The node becomes black. After that players take turns. In each turn, a player moves the chip from the current position to an ancestor or descendant node, as long as the node is not black. This node also becomes black. The player who cannot move the chip looses.
Who wins the game?
An ancestor of a node v in a rooted tree is any node on the path between v and the root of the tree.
A descendant of a node v in a rooted tree is any node w such that node v is located on the path between w and the root of the tree.
We consider that the root of the tree is 1.
Input
The first line contains one integer n (1≤n≤100000)n(1≤n≤100000) — the number of nodes.Each of the next n−1n−1 lines contains two integers uu and vv (1≤u,v≤n)(1≤u,v≤n) — the edges of the tree. It is guaranteed that they form a tree.
Output
In a single line, print “Alice” (without quotes), if Alice wins. Otherwise, print “Bob”.
输出时每行末尾的多余空格,不影响答案正确性
4
1 2
2 3
3 4
Bob
7
2 1
2 6
1 3
2 5
7 2
2 4
Alice
解题思路:
由题目可以知道,该游戏为一人走一步,并且只能在当前位置进行移动,那么我们可以考虑将每两个点进行匹配;
我们可以考虑,假设有n个点,那么这几个点分为n / 2组,两两进行匹配的话可以得到集合**{(p1 , p2) , (p3 , p4) , …(pn-1, pn+1)}**;
第一种情况:
如果所有的点都进行了匹配,即完美匹配,我们可以推出,先手每走一步,后手就只能走与之相匹配的点上,则最大匹配是完美匹配的情况下,后手必赢,即B必赢;
第二种情况:
该图的最大匹配如果不是完美匹配,即还有点无法进行匹配(点之间无连线),那么如果先手选择一个不在匹配内的点时,可以推得先手必赢,即A必赢;
考虑到这里后,只需要解决该图的最大匹配数是否为完美匹配就可以解决这道题目;使用dfs则可以找到该图的完美匹配数;
这里我们设置一个数组s[ ] 来进行dfs,s[ i ]表示以 i 为根节点的子树所剩下的未匹配的节点的个数,那么我们只要从叶子节点进行贪心,往上匹配即可;
AC代码:
#include
#include
#include
#include
#include
#include
#include