「hdu5002」Tree

2014年12月13日3,8080
Problem Description
You are given a tree with N nodes which are numbered by integers 1..N. Each node is associated with an integer as the weight.

Your task is to deal with M operations of 4 types:

1.Delete an edge (x, y) from the tree, and then add a new edge (a, b). We ensure that it still constitutes a tree after adding the new edge.

2.Given two nodes a and b in the tree, change the weights of all the nodes on the path connecting node a and b (including node a and b) to a particular value x.

3.Given two nodes a and b in the tree, increase the weights of all the nodes on the path connecting node a and b (including node a and b) by a particular value d.

4.Given two nodes a and b in the tree, compute the second largest weight on the path connecting node a and b (including node a and b), and the number of times this weight occurs on the path. Note that here we need the strict second largest weight. For instance, the strict second largest weight of {3, 5, 2, 5, 3} is 3.

 

Input
The first line contains an integer T (T<=3), which means there are T test cases in the input.

For each test case, the first line contains two integers N and M (N, M<=10^5). The second line contains N integers, and the i-th integer is the weight of the i-th node in the tree (their absolute values are not larger than 10^4).

In next N-1 lines, there are two integers a and b (1<=a, b<=N), which means there exists an edge connecting node a and b.

The next M lines describe the operations you have to deal with. In each line the first integer is c (1<=c<=4), which indicates the type of operation.

If c = 1, there are four integers x, y, a, b (1<= x, y, a, b <=N) after c.
If c = 2, there are three integers a, b, x (1<= a, b<=N, |x|<=10^4) after c.
If c = 3, there are three integers a, b, d (1<= a, b<=N, |d|<=10^4) after c.
If c = 4 (it is a query operation), there are two integers a, b (1<= a, b<=N) after c.

All these parameters have the same meaning as described in problem description.

Output
For each test case, first output “Case #x:”” (x means case ID) in a separate line.

For each query operation, output two values: the second largest weight and the number of times it occurs. If the weights of nodes on that path are all the same, just output “ALL SAME” (without quotes).

Sample Input
2 3 2 1 1 2 1 2 1 3 4 1 2 4 2 3 7 7 5 3 2 1 7 3 6 1 2 1 3 3 4 3 5 4 6 4 7 4 2 6 3 4 5 -1 4 5 7 1 3 4 2 4 4 3 6 2 3 6 5 4 3 6
Sample Output
Case #1: ALL SAME 1 2 Case #2: 3 2 1 1 3 2 ALL SAME
题解
1:删边加边
2:路径修改
3:路径加
4:询问路径次大值及其个数
为了实现4操作,对每个节点维护最大值与次大值及个数,记为mx1,mx2,c1,c2,设x的值为v
比如往节点x加入c个值为val的数,用 solve(x,val,c) 处理
则应分四种情况维护x的信息
if(val>mx1[x])mx2[x]=mx1[x],mx1[x]=val,c2[x]=c1[x],c1[x]=c;
else if(val==mx1[x])c1[x]+=c;
else if(val>mx2[x])mx2[x]=val,c2[x]=c;
else if(val==mx2[x])c2[x]+=c;
设其左右儿子为l,r在update时只需要
清空x的信息
solve(x,v[x],1);
solve(x,mx1[l],c1[l]),solve(x,mx2[l],c2[l]);
solve(x,mx1[r],c1[r]),solve(x,mx2[r],c2[r]);
这样写应该会比较清楚

 

avatar
  Subscribe  
提醒