A tale of two trees

0

0 votes
Graph, Hard, Algorithms
Problem

Tree is defined as an undirected graph of N nodes and N1 edges that does not contain any cycles.

You are given two trees with N nodes rooted at 1. Each node has a colour associated with it, either white or black. You need to do perform Q operations of the following three kinds:

  1. Given a node U in second tree, swap the colour of all nodes in Us subtree.

  2. You are given 3 integers U,V and W where nodes U and V belong to the first tree, W belongs to the second tree and V lies in the subtree of U. Let the parent of W be P. You need to attach Ws subtree as a child of V and Us subtree as child of P.

  3. Given a node U in the second tree, find the number of white nodes in Us subtree.

Input:

First line of input contains 2 space separated integers N and Q. Next line contains N space separated integers. If the ith integer is 1 then the ith node in first tree is coloured white, else black. Next line contains N space separated integers. If the ith integer is 1 then the ith node in second tree is coloured white, else black.

Each of the next N1 lines contain two integers u and v denoting edges of the first tree. The next N1 lines contain edges of the second tree in the same format.

Each of the next Q lines contain queries. The first integer denotes the type of query. If it is a type 1 or type 3 query, next integer denotes U (as defined in the problem statement). If it is a type 2 query, next three integers denote U,V and W (as defined in the problem statement).

Output:

For each query of the third kind, print the number of white nodes in Us subtree.

Constraints:

2N2×105

1Q2×105

1U,VN

2WN

Time Limit: 4
Memory Limit: 256
Source Limit:
Explanation

For the 1st query, number of white nodes in the subtree of 4 (in second tree) is 1.

Editor Image

?