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
分析:考虑长度为L的链,它的前缀gcd最多有log L个,然后我们要修改的那个点一定是两个不同的前缀gcd的交界,不然可以证明修改无意义,所以每次log n的复杂度枚举要修改的点就可以了。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5+5;
int n,a[N],dep[N],pre[N],last[N],w[N][31],f[N][31];
vector<int> G[N];
void init()
{
for(int j = 1;(1<<j) <= n;j++)
for(int i = 1;i <= n;i++)
{
f[i][j] = f[f[i][j-1]][j-1];
w[i][j] = __gcd(w[f[i][j-1]][j-1],w[i][j-1]);
}
}
int got(int x,int y)
{
int tmp = a[x];
for(int i = 20;i >= 0;i--)
if(dep[f[x][i]] > dep[y])
{
tmp = __gcd(tmp,w[x][i]);
x = f[x][i];
}
return tmp;
}
void dfs(int u,int fa)
{
dep[u] = dep[fa] + 1;
f[u][0] = fa;
w[u][0] = fa ? __gcd(a[fa],a[u]) : a[u];
if(!pre[fa]) pre[u] = a[u];
else pre[u] = __gcd(pre[fa],a[u]);
if(pre[u] != pre[fa]) last[u] = u;
else last[u] = last[fa];
for(int v : G[u])
if(v != fa) dfs(v,u);
}
int work(int u)
{
int ans = -1;
int p = last[u];
while(p)
{
int tmp = pre[f[p][0]];
if(p != u)
{
if(tmp) tmp = __gcd(tmp,got(u,p));
else tmp = got(u,p);
}
ans = max(ans,tmp);
p = last[f[p][0]];
}
return ans;
}
int main()
{
scanf("%d",&n);
for(int i = 1;i <= n;i++) scanf("%d",&a[i]);
for(int i = 1;i < n;i++)
{
int u,v;
scanf("%d%d",&u,&v);
G[u].push_back(v);
G[v].push_back(u);
}
dfs(1,0);
init();
cout<<a[1]<<" ";
for(int i = 2;i <= n;i++) cout<<work(i)<<" ";
}

本文介绍了一种使用树形动态规划解决路径最大公约数(GCD)问题的方法。通过预处理每个节点到根节点路径上的GCD信息,并考虑修改某个节点数值对路径GCD的影响,实现了高效求解。文章提供了完整的代码实现。
429

被折叠的 条评论
为什么被折叠?



