Codeforces - Ilya And The Tree

题目链接:Codeforces - Ilya And The Tree


对于每个点其实只有删除或者不删除。

所以从上往下做记忆化即可。


AC代码:

#pragma GCC optimize("-Ofast","-funroll-all-loops")
#include<bits/stdc++.h>
//#define int long long
using namespace std;
const int N=2e5+10;
int n,a[N],res[N];
vector<int> g[N];	unordered_map<int,int> mp[N][2];
inline void add(int a,int b){g[a].push_back(b),g[b].push_back(a);}
void dfs(int x,int fa,int isc,int gd){
	if(mp[x][isc][gd])	return;	mp[x][isc][gd]=1;
	int tmp=__gcd(gd,a[x]);
	res[x]=max(res[x],tmp);
	if(!isc) res[x]=max(res[x],gd);
	for(auto to:g[x])	if(to!=fa){
		dfs(to,x,isc,tmp);
		if(!isc)	dfs(to,x,1,gd);
	}
}
signed main(){
	cin>>n;
	for(int i=1;i<=n;i++)	scanf("%d",&a[i]);
	for(int i=1,x,y;i<n;i++)	scanf("%d %d",&x,&y),add(x,y);
	dfs(1,1,0,0);
	for(int i=1;i<=n;i++)	printf("%d ",res[i]);
	return 0;
}
发布了809 篇原创文章 · 获赞 246 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/weixin_43826249/article/details/105316795
今日推荐