C. 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
2
6 2
1 2
output
6 6
input
3
6 2 3
1 2
1 3
output
6 6 6
input
1
10
output
10
【解题报告】
题意,给出一棵生成树,每个节点都有一个值,现在要求出每个节点的美丽值的最大值,美丽值的定义为从根节点到该节点(包含)路径上所有点的值的gcd,求解每个点时可以把路径上某一个点的值变为0。你可以认为每个点美丽值的求解是独立的。
显然,我们可以进行树上DFS。
我们用dp数组来保存每个节点在路径上没有改变值的时候的gcd,然后先单独考虑当前点不选的美丽值即dp[u]。然后用vector[u]数组来保存节点v的父亲节点的美丽值的所有可能情况,这里的情况有可能是改变了值后的,也可能没有,但由于我们在这一步一定会算入节点v的值(不算的情况单独考虑),所以满足最多只改变一次值的要求。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
using namespace std;
#define N 200010
int n;
int a[N],dp[N];
int cnt,head[N];
vector<int>vec[N];
struct Edge{int to,nxt;}e[N<<1];
int gcd(int a,int b)
{
return b?gcd(b,a%b):a;
}
void adde(int u,int v)
{
e[++cnt].to=v;e[cnt].nxt=head[u];head[u]=cnt;
e[++cnt].to=u;e[cnt].nxt=head[v];head[v]=cnt;
}
void dfs(int u,int pre)
{
for(int i=head[u];~i;i=e[i].nxt)
{
int v=e[i].to;
if(v==pre) continue;
dp[v]=gcd(dp[u],a[v]);
vec[v].push_back(dp[u]);
for(int i=0;i<vec[u].size();++i)
{
vec[v].push_back(gcd(vec[u][i],a[v]));
}
sort(vec[v].begin(),vec[v].end());
vec[v].erase(unique(vec[v].begin(),vec[v].end()),vec[v].end());
dfs(v,u);
}
}
int main()
{
cnt=0;
memset(head,-1,sizeof(head));
scanf("%d",&n);
for(int i=1;i<=n;++i) scanf("%d",&a[i]);
for(int i=0;i<n-1;++i)
{
int u,v;
scanf("%d%d",&u,&v);
adde(u,v);
}
dp[1]=a[1];
vec[1].push_back(0);
dfs(1,-1);
for(int i=1;i<=n;++i)
{
dp[i]=max(dp[i],vec[i].back());
}
for(int i=1;i<=n;i++)
{
printf("%d ",dp[i]);
}
return 0;
}