Ilya And The Tree——http://codeforces.com/problemset/problem/842/C

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 0or 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 ≤ 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

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 

题意:求一颗树路径上的点,从节点1但x节点的最大公约数;

条件:你可以把1到x路径上的任意一个点变成0;也可以不变;

这种情况就要考虑每一个1到x节点的路径中所进过的点都可能为0,的情况;

我们可以通过前面的节点来更新后面的数据;

放在set集合里;下一次穿进去一个心的set里并更新,遍历求最大公约数

#include <cstdio>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <set>
#include <vector>
#include <map>

using namespace std;
typedef long long LL;
const int maxn = 2e5 + 5;


int n;
int a[maxn];
int ans[maxn];
int vis[maxn];
vector <int> ve[maxn];
int gcd(int x, int y)
{
	if(y == 0)  return x;
	else return gcd(y, x % y);
}

void dfs(int x,int g, set <int> s)//g为前面的点都不为0  set_s表示前面的路径中有一个点为0的最大公约数的集合
{
	set <int>sss;
	int maxx = 0;
	set <int> :: iterator it;
	for(it = s.begin();it != s.end();it++)
	{
		int g0 = *it;
		g0 = gcd(g0, a[x]);  // 前面有点为0与当前值取最大公约数
		maxx = max(maxx, g0); //更新
		sss.insert(g0);
	}
	maxx = max(g, maxx);  // maxx更新为前面有0,和当前为0 两种不同情况的最大公约数的最大;
	ans[x] = maxx;
	sss.insert(g);  //两种情况的值都在sss里
	int next = gcd(g, a[x]);
	for(int i = 0;i < ve[x].size();i++)
	{
		int r = ve[x][i];
		if(!vis[r])
		{
			vis[r] = 1;
			dfs(r, next, sss);
			vis[r] = 0;
		}
	}
}


int main()
{
	scanf("%d",&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);
		ve[u].push_back(v);
		ve[v].push_back(u);
	}
	set <int> ss;
	vis[1] = 1;
	dfs(1, a[0], ss);
	ans[1] = a[1];
	for(int i = 1;i <= n;i++)
	{
		if(i == 1) printf("%d",ans[i]);
		else printf(" %d",ans[i]);
	}
	printf("\n");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/strawberry_595/article/details/81088233
今日推荐