Codeforces 842 C. Ilya And The Tree (dfs)

网友投稿 714 2022-08-26

Codeforces 842 C. Ilya And The Tree (dfs)

Codeforces 842 C. Ilya And The Tree (dfs)

Description

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·10^5).Next line contains n integer numbers ai (1 ≤ i ≤ n, 1 ≤ ai ≤ 2·10^5).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.

Sample Input

36 2 31 21 3

Sample Output

6 6 6

题意

一棵根节点为 1 的树,每个节点都有权值,求从根节点到每个点路径所有权值的最大 gcd 。(我们可以把每条路径上一个点的权值变为 0 )

思路

显然,我们可以通过 dfs 来求解这个问题。

对于每一个点 x ,其结果是一个集合。

我们可以不选择 x (权值变为 0 ),此时到这里的贡献为从根节点到当前位置除 x 以外所有数的 gcd ;我们也可以选择 x ,此时的贡献有:

从根节点到当前位置所有数的 gcd当前数与其父节点所有符合条件的值计算 gcd

然后对于每一个数所拥有的一个集合,取最大值输出即可。

AC 代码

#include using namespace std;const int maxn=2e5+10;int a[maxn],n;vectorg[maxn];sets[maxn];void dfs(int x,int fa,int now){ for(auto p:s[fa]) s[x].insert(__gcd(p,a[x])); s[x].insert(now); //当前点置零 now=__gcd(now,a[x]); s[x].insert(now); //当前点保留 for(auto p:g[x]) if(p!=fa) dfs(p,x,now);}int main(){ scanf("%d",&n); for(int i=1; i<=n; i++) scanf("%d",a+i); int u,v; for(int i=1; i

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:HDU 6156 Palindrome Function (数位dp)
下一篇:GacLib使用方法(Gaclib)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~