Problem F. Grab The Tree (HDU-6324)

 Problem F. Grab The Tree

Little Q and Little T are playing a game on a tree. There are nn vertices on the tree, labeled by 1,2,...,n1,2,...,n, connected by n1n−1 bidirectional edges. The ii-th vertex has the value of wiwi. 
In this game, Little Q needs to grab some vertices on the tree. He can select any number of vertices to grab, but he is not allowed to grab both vertices that are adjacent on the tree. That is, if there is an edge between xx and yy, he can't grab both xx and yy. After Q's move, Little T will grab all of the rest vertices. So when the game finishes, every vertex will be occupied by either Q or T. 
The final score of each player is the bitwise XOR sum of his choosen vertices' value. The one who has the higher score will win the game. It is also possible for the game to end in a draw. Assume they all will play optimally, please write a program to predict the result. 

InputThe first line of the input contains an integer T(1T20)T(1≤T≤20), denoting the number of test cases. 
In each test case, there is one integer n(1n100000)n(1≤n≤100000) in the first line, denoting the number of vertices. 
In the next line, there are nn integers w1,w2,...,wn(1wi109)w1,w2,...,wn(1≤wi≤109), denoting the value of each vertex. 
For the next n1n−1 lines, each line contains two integers uu and vv, denoting a bidirectional edge between vertex uu and vv. 
OutputFor each test case, print a single line containing a word, denoting the result. If Q wins, please print Q. If T wins, please print T. And if the game ends in a draw, please print D. 

Sample Input

1
3
2 2 2
1 2
1 3

Sample Output

Q

题意:
给出一棵n个节点的树,每个节点有一个权值,Q和T玩游戏,Q先选一些不相邻的节点,T选剩下的节点,每个人的分数是所选节点的权值的异或和,权值大的胜出,问胜出的是谁。

官方题解:

sum为所有点权的异或和,A为先手得分,B为后手得分。

  • sum=0,则A=B,故无论如何都是平局。
  • 否则考虑sum二进制下最高的1所在那位,一定有奇数个点那一位为1。若先手拿走任意一个那一位为1的点,则B该位为0,故先手必胜。

时间复杂度O(n)

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 using namespace std;
 5 const int maxn=1e5+10;
 6 int a[maxn];
 7 int main()
 8 {
 9     int casen;
10     int n;
11     scanf("%d",&casen);
12     while(casen--)
13     {
14         int ans=0;
15         scanf("%d",&n);
16         for(int i=1;i<=n;i++)
17         {
18             scanf("%d",&a[i]);
19             ans^=a[i];
20         }
21         int x,y;
22         for(int i=1;i<n;i++)
23         {
24             scanf("%d%d",&x,&y);
25         }
26         if(ans==0)
27             printf("D\n");
28         else
29             printf("Q\n");
30     }
31 }

 

posted @ 2018-10-22 09:45  *starry*  阅读(155)  评论(0编辑  收藏  举报