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 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 ≤ n1 ≤ ai ≤ 2·105).

Each of next n - 1 lines contains two integer numbers x and y (1 ≤ x, y ≤ nx ≠ 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
Copy
2
6 2
1 2
output
6 6 
input
Copy
3
6 2 3
1 2
1 3
output
6 6 6 
input
Copy
1
10
output
10 


题意:给一张图,每个节点有一个权值,一个节点的beauty值=gcd(root  to now's weight)   【允许在一条路径上有一个数为0】,求出每个节点的最大beauty值

思路:对于当前的数x,其beauty值有两种情况

①  把这个数设为0,前面所有值是原值

②这个数是原来的数,前面的值都是原值 || 父亲满足的情况


#include<bits/stdc++.h>
#define PI acos(-1.0)
using namespace std;
typedef long long ll;

const int N=2e5+6;
const int MOD=1e9+7;
const int INF=0x3f3f3f3f;
vector <int> edge[N];
set<int> st[N];
int a[N],vis[N];

void dfs(int u,int fa,int gcd){

    st[u].insert(__gcd(gcd,a[u])); // ALL GCD
    st[u].insert(gcd); // let a[u]=0                                                            
    for(set<int>::iterator it=st[fa].begin();it!=st[fa].end();it++){
        int t=*it;
        st[u].insert(__gcd(t,a[u]));
    }
    gcd=__gcd(gcd,a[u]);
    vis[u]=1;
    for(int i=0;i<edge[u].size();++i){
        int v=edge[u][i];
        if(!vis[v]){
            dfs(v,u,gcd);
        }
    }
}

int main(void){
    int n;
    cin >> n;
    for(int i=1;i<=n;i++)   scanf("%d",&a[i]);
    for(int i=1;i<=n-1;i++){
        int u,v;
        scanf("%d%d",&u,&v);
        edge[u].push_back(v);
        edge[v].push_back(u);
    }
    dfs(1,0,0);
    for(int i=1;i<=n;i++){
        if(i==1)    printf("%d",*st[i].rbegin());
        else printf(" %d",*st[i].rbegin());
    }
    return 0;
}