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
题目大意:对于每一个顶点可以把从根节点到这个点的路径的某一个点的值变为0,求出每一条路的最大gcd
题目思路:这道题最关键的一点就是分析出复杂度,切入点就是每一个数的约数对与2^63这个范围来说最大就是63个而已,所以我们可以直接把这题当做模拟来做,对于当前的这个节点,把他与父节点的所有情况的存下来,深搜到叶子节点,注意一下去重就行了,,去重可以用set实现,也可以用vector加uinque复杂度为n*logn*logn
ac代码:#include<cstdio> #include<iostream> #include<sstream> #include<cstring> #include<algorithm> #include<vector> #define LL long long #define INF 0x3f3f3f3f using namespace std; const int maxn = 2e5+5; int head[maxn]; int tot = 0; int a[maxn]; int n; int dp[maxn]; vector<int>Q[maxn]; struct node { int u,v; int net; }E[maxn*2]; int gcd(int a,int b) { return b==0?a:gcd(b,a%b); } void init() { memset(head,-1,sizeof(head)); tot = 0; } void build(int u,int v) { E[tot].u = u; E[tot].v = v; E[tot].net = head[u]; head[u] = tot++; } int cmp(int a,int b) { return a>b; } int dfs(int u,int fa,int pregcd) { int tmpgcd = gcd(0,pregcd); Q[u].push_back(tmpgcd); int nowgcd = gcd(a[u],pregcd); Q[u].push_back(nowgcd); int len = Q[fa].size(); for(int i = 0;i<len;i++){ Q[u].push_back(gcd(a[u],Q[fa][i])); } sort(Q[u].begin(),Q[u].end()); Q[u].erase(unique(Q[u].begin(),Q[u].end()),Q[u].end()); for(int i = head[u];~i;i = E[i].net) { int to = E[i].v; if(to==fa) continue; dfs(to,u,nowgcd); } } int main() { while(~scanf("%d",&n)) { init(); for(int i = 0;i<=n;i++){ Q[i].clear(); } memset(dp,0,sizeof(dp)); for(int i = 1;i<=n;i++){ scanf("%d",&a[i]); } for(int i = 0;i<n-1;i++){ int a,b; scanf("%d%d",&a,&b); build(a,b); build(b,a); } dfs(1,0,0); for(int i = 1;i<=n;i++){ int len = Q[i].size(); printf("%d%c",Q[i][len-1],i==n?'\n':' '); } } }