842C Ilya And The Tree

来源:互联网 发布:虚拟机网络没有连接 编辑:程序博客网 时间:2024/06/07 03:17
C. Ilya And The Tree
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Ilya is very fond of graphs, especially trees. During his last trip to the forest Ilya found a very interesting tree rooted at vertex1. There is an integer number written on each vertex of the tree; the number written on vertexi 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 tox, including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to0 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 numbersx 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, wherei-th number equals to maximum possible beauty of vertexi.


题意:给你一颗以1位根的有根数,每个节点都有一个权值,对于每个节点他的价值为从它到根节点所经过所有节点权值的最大公约数,而对于每个节点的计算,都可以将

某个节点的权值变为0,蚊你每个节点的价值的最大值。



这题搜一搜,没到一个节点分解因数记录因数出现次数,那么出现次数大于等于dep-1的最大因数一定就是那个点的最大价值了,注意回溯是需要减去该点的贡献。


#include<stdio.h>#include<algorithm>#include<math.h>#include<vector>using namespace std;const int maxm = 200005;vector<int>v[maxm];int a[maxm], dp[3][maxm], f[maxm] = { 0 }, sum[maxm];void dfs(int k, int pre, int dep, int ans){int rev = ans, xx, ii;ans = 0;xx = sqrt(a[k]);for (int i = 1;i <= xx;i++){if (a[k] % i == 0){sum[i]++;ii = a[k] / i;if (ii != i) sum[ii]++;if (sum[i] == (dep - 1))rev = max(rev, i);if (sum[i] == dep)rev = max(rev, i), ans = max(ans, i);if (ii == i) continue;if (sum[ii] == (dep - 1))rev = max(rev, ii);if (sum[ii] == dep)rev = max(rev, ii), ans = max(ans, ii);}}f[k] = rev;for (int i = 0;i < v[k].size();i++){int xx = v[k][i];if (xx == pre) continue;dfs(xx, k, dep + 1, ans);}for (int i = 1;i <= xx;i++){if (a[k] % i == 0){sum[i]--;ii = a[k] / i;if (ii != i) sum[ii]--;}}}int main(){int n, i, j, k, sum, x, y;scanf("%d", &n);for (i = 1;i <= n;i++) scanf("%d", &a[i]);for (i = 1;i < n;i++){scanf("%d%d", &x, &y);v[x].push_back(y);v[y].push_back(x);}dfs(1, 0, 1, 0);for (i = 1;i <= n;i++)printf("%d ", f[i]);printf("\n");return 0;}