[CF1101D GCD Counting] 树形DP

[GCD Counting]

Code


#include
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
using namespace std;
const int N=5e5;
struct node{int y,n;}e[N];
int lin[N],f[200100][20],len=1,val,ans=0,n,x,y;
vector p[N];
void read(int x,int y)
{e[++len].y=y,e[len].n=lin[x],lin[x]=len;}
void work(int x,int val){
	rep(i,2,sqrt(val)){
		if(val%i)continue;
		while(val&&val%i==0)val/=i;
		ans=1;
		p[x].push_back(i);
	}
	if(val>1)ans=1,p[x].push_back(val);
}
void dfs(int x,int fa){
	for(int i=lin[x];i;i=e[i].n){
		int y=e[i].y;
		if(y==fa)continue;
		dfs(y,x);
		rep(j,0,(int)p[x].size()-1){
			rep(k,0,(int)p[y].size()-1){
				if(p[x][j]!=p[y][k])continue;
				ans=max(ans,f[x][j]+f[y][k]);
				f[x][j]=max(f[x][j],f[y][k]+1);
			}
		}
	}
}
int main()
{
	//freopen("a.in","r",stdin);
	scanf("%d",&n);
	rep(i,1,n){
		scanf("%d",&val);
		work(i,val);
	}
	rep(i,1,n)rep(j,0,19)f[i][j]=1;
	rep(i,2,n){scanf("%d%d",&x,&y);read(x,y),read(y,x);}
	dfs(1,0);
	printf("%d",ans);
	return 0;
}

 

你可能感兴趣的:(动态规划)