最近在做codeforces上面的题,感觉质量挺高的,而且区分难易,便于入手。今天做到的这题考察的东西不少,由于本人水平不济(其实是懒),只能看看别人写的代码,找到一个写的挺好的,多多学习。
原题链接:Ilya And The Tree
Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex 1. There is an integer number written on each vertex of the tree; the number written on vertex i is equal to ai.
Ilya believes that the beauty of the vertex x is the greatest common divisor of all numbers written on the vertices on the path from the root to x, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 or leave all vertices unchanged. Now for each vertex Ilya wants to know the maximum possible beauty it can have.
For each vertex the answer must be considered independently.
The beauty of the root equals to number written on it.
Input
First line contains one integer number n — the number of vertices in tree (1 ≤ n ≤ 2·105).
Next line contains n integer numbers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 2·105).
Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ n, x ≠ y), which means that there is an edge (x, y) in the tree.
Output
Output n numbers separated by spaces, where i-th number equals to maximum possible beauty of vertex i.
Examples
input
|
|
output
|
|
input
|
|
output
|
|
input
|
|
output
|
|
代码如下:
|
|
转自:http://blog.csdn.net/yasola/article/details/77711827
知识点补充:
~-1
的结果是0。if(一个负数) 是会运行后面的语句的。
__gcd(a,b)
今后直接拿来用,省得自己写了。sort(dp[u].begin(), dp[u].end());
dp[u].erase(unique(dp[u].begin(), dp[u].end()), dp[u].end());//去重
注意unique的用法,使用前要先排序,配合erase使用效果很好。