您的位置:首页 > 其它

Codeforces Round #430 (Div. 2) C. Ilya And The Tree

2017-08-30 12:01 537 查看

地址:http://codeforces.com/contest/842/problem/C

题目:

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 ≤ 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 66 
input
1
10
output
10

 

 思路:

  用set<int>dp[K]来表示走到节点i时前面修改一个数时的所有可能值,然后转移即可。

  看起来是n^2的dp,但约数个数是非常少的。

#include <bits/stdc++.h>

using namespace std;

#define MP make_pair
#define PB push_back
typedef long long LL;
typedef pair<int,int> PII;
const double eps=1e-8;
const double pi=acos(-1.0);
const int K=1e6+7;
const int mod=1e9+7;

int v[K];
vector<int>mp[K];
set<int>dp[K];

void dfs(int x,int f,int sum)
{
for(auto &y:dp[f])
dp[x].insert(__gcd(v[x],y));
dp[x].insert(__gcd(sum,v[x]));
dp[x].insert(__gcd(0,sum));
for(auto &y:mp[x])
if(y!=f)
dfs(y,x,__gcd(v[x],sum));
}
int main(void)
{
int n;
cin>>n;
for(int i=1;i<=n;i++)
scanf("%d",v+i);
for(int i=1,x,y;i<n;i++)
scanf("%d%d",&x,&y),mp[x].PB(y),mp[y].PB(x);
dfs(1,0,0);
for(int i=1;i<=n;i++)
printf("%d ",*dp[i].rbegin());
return 0;
}

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: