You are given a tree consisting of n vertices. A number is written on each vertex; the number on vertex i is equal to ai.
Let’s denote the function g(x,y) as the greatest common divisor of the numbers written on the vertices belonging to the simple path from vertex x to vertex y (including these two vertices). Also let’s denote dist(x,y) as the number of vertices on the simple path between vertices x and y, including the endpoints. dist(x,x)=1 for every vertex x.
Your task is calculate the maximum value of dist(x,y) among such pairs of vertices that g(x,y)>1.
Input
The first line contains one integer n — the number of vertices (1≤n≤2⋅105).
The second line contains n integers a1, a2, …, an (1≤ai≤2⋅105) — the numbers written on vertices.
Then n−1 lines follow, each containing two integers x and y (1≤x,y≤n,x≠y) denoting an edge connecting vertex x with vertex y. It is guaranteed that these edges form a tree.
Output
If there is no pair of vertices x,y such that g(x,y)>1, print 0. Otherwise print the maximum value of dist(x,y) among such pairs.
Examples
inputCopy
3
2 3 4
1 2
2 3
outputCopy
1
inputCopy
3
2 3 4
1 3
2 3
outputCopy
2
inputCopy
3
1 1 1
1 2
2 3
outputCopy
0
题意:
给你一棵树,每个点都有一个权值,问你树上GCD大于1的最长距离为多少、
题解:
对于一个节点,最长距离的情况要么是它的两条儿子,要么是它的一条儿子和父亲这两种情况,所以从上到下的时候做是不行的,那么只有回溯的时候做。它的要求是GCD>1,那么我们假设所有数的因子都是质因子,这样会省一些时间。我们枚举当前点的所有质因子,看看这个质因子在儿子节点最长能走多少,然后选择最长的两条。注意第二种父亲的情况,那么我们要记录最长的链的长度。
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define pa pair<int,int>
const int N=2e5+5;
int p[N],np[N],cnt;
vector<int>vec[N];
map<int,int>mp[N];
void init()//预处理相关
{
np[1]=1;
for(ll i=2;i<N;i++)
{
if(!np[i])
{
p[++cnt]=i;
for(ll j=i*i;j<N;j+=i)
np[j]=1;
}
}
for(int i=2;i<N;i++)
{
int x=i;
for(int j=1;j<=cnt&&p[j]<=sqrt(x);j++)
{
if(!np[x])
break;
if(x%p[j]==0)
{
while(x%p[j]==0)
x/=p[j];
vec[i].push_back(p[j]);
}
}
if(x!=1)
vec[i].push_back(x);
}
}
struct node//链式前向星相关
{
int to,next;
}e[N*2];
int tot,head[N],a[N];
void add(int x,int y)
{
e[tot].to=y;
e[tot].next=head[x];
head[x]=tot++;
}
int ans;
void dfs(int x,int f)//核心
{
for(int i=head[x];~i;i=e[i].next)
{
int v=e[i].to;
if(v==f)
continue;
dfs(v,x);
}
for(int i=0;i<vec[a[x]].size();i++)
{
int yz=vec[a[x]][i];
int m=0,sm=0;
for(int j=head[x];~j;j=e[j].next)
{
int ne=e[j].to;
if(mp[ne][yz]>m)
sm=m,m=mp[ne][yz];
else if(mp[ne][yz]>sm)
sm=mp[ne][yz];
}
mp[x][yz]=m+1;
ans=max(ans,m+sm+1);
}
}
int main()
{
init();
memset(head,-1,sizeof(head));
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%d",&a[i]);
int x,y;
for(int i=1;i<n;i++)
scanf("%d%d",&x,&y),add(x,y),add(y,x);
dfs(1,0);
printf("%d\n",ans);
return 0;
}