Accurate XOR Codechef Problem Solution ( TREEXOR )

Chef has a tree consisting of nodes, rooted at node . The parent of the node in the tree is the node .

Chef wants to assign a binary value (0 or 1) to every node of the tree. The Xor-value of a node is defined as the bitwise XOR of all the binary values present in the subtree of that node.

Help Chef to assign values to the nodes of the tree in such a way that the sum of Xor-value of all the nodes in the tree is exactly .

It can be shown that such an assignment always exists. If there are multiple possible answers, you may print any of them.

Input Format

  • The first line of input will contain a single integer , denoting the number of test cases.
  • The first line of each test case contains two space-separated integers and , denoting the number of vertices in the tree and the required sum of Xor-value respectively.
  • The second line of each test case contains space-separated integers , where denotes the parent-node of the node.

Output Format

For each test case, print on a new line a binary string of length where the character of the string denotes the binary value assigned to node . If there are multiple ways to assign values to the node, you can do it in any way.

Constraints

  • for each
  • The sum of over all test cases won’t exceed .

Sample Input 1

3
2 0
1
3 1
1 1
5 2
1 2 2 1

Sample Output 1

00
100
11010

Explanation

Test case : The Xor-value of both nodes is 0.

Test case : The Xor-value of the node is and the remaining nodes have Xor-value

Test case : The Xor-value of the nodes is and the remaining nodes have Xor-value .

				
					using namespace std;
int done;
int dfs(vector<vector<int>>&adj,int x,vector<char>&ans,vector<bool>&vi){
    int y=0;
    for(auto j:adj[x]){
        if(vi[j])continue;
        vi[j]=true;
        y+=dfs(adj,j,ans,vi);
    }
    if(done){
        ans[x]='0'+1-(y%2);
        done--;
        return 1;
    }
    ans[x]='0'+(y%2);
    return 0;
}
int main() {
	int T;
	cin >> T;
	while(T--){
	    int n,k;
	    cin >> n >> k;
	    vector<vector<int>>adj(n+1);
	    for(int i=0;i<n-1;i++){
	        int t;
	        cin >> t;
	        adj[i+2].push_back(t);
	        adj[t].push_back(i+2);
	    }
	    done=k;
	    vector<char>ans(n+1,'0');
	    vector<bool>vi(n+1,false);
	    vi[1]=true;
	    int m=dfs(adj,1,ans,vi);
	    for(int i=1;i<=n;i++)cout << ans[i];
	    cout << endl;
	}
	return 0;
}
				
			

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published.