地址:http://codeforces.com/contest/842/problem/C
题目:
2 seconds
256 megabytes
standard input
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.
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
思路:
用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-;
const double pi=acos(-1.0);
const int K=1e6+;
const int mod=1e9+; 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(,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=;i<=n;i++)
scanf("%d",v+i);
for(int i=,x,y;i<n;i++)
scanf("%d%d",&x,&y),mp[x].PB(y),mp[y].PB(x);
dfs(,,);
for(int i=;i<=n;i++)
printf("%d ",*dp[i].rbegin());
return ;
}