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.
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 n numbers separated by spaces, where i-th number equals to maximum possible beauty of vertex i.
2 6 2 1 2
6 6
3 6 2 3 1 2 1 3
6 6 6
1 10
10
思路 : 对于树上的每一个节点,它的最大值或者等于把该节点变为0得到的结果,即从根节点到父亲节点没有变0得到的公分母;或者父亲节点里面所有可能的gcd和该点的最大公分母的最大值。
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <cstring>
#include <map>
#include <climits>
#include <vector>
using namespace std;
int gcd(int a,int b)
{
return b == 0 ? a : gcd(b,a%b);
}
vector <int > vc[1000000];
vector <int> dp_[1000006];//记录每个点所有可能的gcd
int a[1000006];
int dp[1000005];// 记录不变0的gcd
int mk[1000000];
void dfs(int cur)
{
for(int i = 0; i < vc[cur].size(); i++)
{
int tmp = vc[cur][i];
if(mk[tmp]) continue;
dp[tmp] = gcd(a[tmp],dp[cur]);
dp_[tmp].push_back(dp[cur]);
for(int j = 0; j < dp_[cur].size(); j++)
{
int x = gcd(a[tmp],dp_[cur][j]);
dp_[tmp].push_back(x);
}
sort(dp_[tmp].begin(),dp_[tmp].end());//去重,减少内存消耗。
dp_[tmp].erase(unique(dp_[tmp].begin(),dp_[tmp].end()),dp_[tmp].end());
mk[tmp] = 1;
dfs(tmp);
mk[tmp] = 0;
}
}
int main()
{
int n;
cin >> n;
for(int i = 1; i <= n; i++)
scanf("%d",&a[i]);
for(int i = 1; i < n; i++)
{
int x,y;
scanf("%d%d",&x,&y);
vc[x].push_back(y);
vc[y].push_back(x);
}
dp[1] = DP[1] = a[1];
dp_[1].push_back(0);
dp_[1].push_back(a[1]);
mk[1] = 1;
dfs(1);
for(int i = 1; i < n; i++)
{
printf("%d ",dp_[i].back());
}
printf("%d\n",dp_[n].back());
return 0;
}