S o l u t i o n \mathrm{Solution} Solution
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 1 1 . There is an integer number written on each vertex of the tree; the number written on vertex i i i is equal to a i a_{i} ai .
Ilya believes that the beauty of the vertex x x x is the greatest common divisor of all numbers written on the vertices on the path from the root to x x x , including this vertex itself. In addition, Ilya can change the number in one arbitrary vertex to 0 0 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.
T r a n s l a t e \mathrm{Translate} Translate
有一个
n
n
n个节点的树,每个点有一个点权,根到这个点的所有点权(包括这个点和根)的gcd
值为这个点的答案. 对于每一个点的答案,你可以删除其到根节点的路径上的至多一个点来使答案最大. 求每个点的答案(最大值). PS:根为
1
1
1号点.
S o l u t i o n \mathrm{Solution} Solution
首先证明一个结论:每一个点的可能数值不超过 n \sqrt n n个。证明如下:
- 当不选这个数字的时候,只存在一个解。
- 当选择这个数字的时候,最后的答案肯定是当前节点权值的因数,因此不超过 n \sqrt n n个。
观察到最后的数字 n ≈ 500 \sqrt n≈500 n≈500,由于最后的数字肯定达不到 n \sqrt n n这个上界,因此我们可以将每一个数字可能的权值用 v e c t o r \mathrm{vector} vector存储即可。
那么我们每一次只要对每一个 v e c t o r \mathrm{vector} vector在添加后去重即可。去重的方法:
c.erase(c.unique(c.begin(),c.end()),c.end())
C o d e \mathrm{Code} Code
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5;
int n;
int a[N], res[N];
vector < int > c, G[N];
int read(void)
{
int s = 0, w = 0; char c = getchar();
while (c < '0' || c > '9') w |= c == '-', c = getchar();
while (c >= '0' && c <= '9') s = s * 10 + c - 48, c = getchar();
return w ? -s : s;
}
int gcd(int a,int b) {
if (b == 0) return a;
if (a == 0) return b;
return gcd(b,a%b);
}
void Dfs(int x,int fa,int sum,vector<int>c)
{
vector < int > C;
res[x] = max(res[x],sum);
for (int i=0;i<G[x].size();++i)
{
int y = G[x][i];
if (y == fa) continue;
C.clear();
for (int j=0;j<c.size();++j) {
C.push_back(gcd(c[j],a[y]));
res[y] = max(res[y],C[j]);
}
C.push_back(sum);
res[y] = max(res[y],sum);
sort(C.begin(),C.end());
C.erase(unique(C.begin(),C.end()),C.end());
Dfs(y,x,gcd(sum,a[y]),C);
}
return;
}
int main(void)
{
n = read();
for (int i=1;i<=n;++i) a[i] = read();
for (int i=1,x,y;i<n;++i)
{
x = read(), y = read();
G[x].push_back(y);
G[y].push_back(x);
}
c.push_back(0);
Dfs(1,0,a[1],c);
for (int i=1;i<=n;++i) printf("%d ", res[i]);
return 0;
}