Problem F. Grab The Tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 199 Accepted Submission(s): 137
Problem Description
Little Q and Little T are playing a game on a tree. There are n vertices on the tree, labeled by 1,2,...,n, connected by n−1 bidirectional edges. The i-th vertex has the value of wi.
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 x and y, he can't grab both x and y. 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.
Input
The first line of the input contains an integer T(1≤T≤20), denoting the number of test cases.
In each test case, there is one integer n(1≤n≤100000) in the first line, denoting the number of vertices.
In the next line, there are n integers w1,w2,...,wn(1≤wi≤109), denoting the value of each vertex.
For the next n−1 lines, each line contains two integers u and v, denoting a bidirectional edge between vertex u and v.
Output
For 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
Source
2018 Multi-University Training Contest 3
树形dp
令dp(i,0/1)表示i的子树,i这个节点是否取的最大异或和
然后就可以状态转移了
#include <bits/stdc++.h>
#define fir first
#define se second
#define mp make_pair
#define pb push_back
#define ll long long
using namespace std;
const int maxn=1e5+10;
const ll mod=998244353;
const double eps=1e-7;
const int maxm=1e6+10;
const int inf=0x3f3f3f3f;
struct Edge{
int u,v,next;
}edge[maxm];
int head[maxn];
int tot=0;
void init(){
memset(head,-1,sizeof(head));
tot=0;
}
void addedge(int u,int v){
edge[tot]=Edge{u,v,head[u]};
head[u]=tot++;
}
int n;
int a[maxn];
int dp[maxn][2];
//dp(i,j)表示i的子树,是否选i的最大异或和
void dfs(int u,int fa){
dp[u][1]=a[u];
dp[u][0]=0;
for (int i=head[u];~i;i=edge[i].next){
int v=edge[i].v;
if (v==fa)continue;
dfs(v,u);
dp[u][0]=max(dp[u][0],max(dp[u][0]^dp[v][1],dp[u][0]^dp[v][0]));
dp[u][1]=max(dp[u][1],dp[u][1]^dp[v][0]);
}
}
int main(){
int t;
scanf("%d",&t);
while (t--){
init();
scanf("%d",&n);
for (int i=1;i<=n;i++)
scanf("%d",&a[i]);
for (int i=1;i<n;i++){
int u,v;
scanf("%d %d",&u,&v);
addedge(u,v);
addedge(v,u);
}
dfs(1,0);
int res=max(dp[1][0],dp[1][1]);
int sum=0;
for (int i=1;i<=n;i++) sum^=a[i];
sum=sum^res;
if (res==sum){
printf("D\n");
}
else if (res>sum){
printf("Q\n");
}
else printf("T\n");
}
return 0;
}