C - Ilya And The Tree Codeforces Round #430 (Div. 2)

时间:2022-10-05 03:45:29

http://codeforces.com/contest/842/problem/C

树 dp

一个数的质因数有限,用set存储,去重

 #include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <time.h>
#include <string>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <queue>
#include <vector>
#include <bitset>
#include <ext/rope>
#include <algorithm>
#include <iostream>
using namespace std;
#define ll long long
#define minv 1e-6
#define inf 1e9
#define pi 3.1415926536
#define E 2.7182818284
const ll mod=1e9+;//
const int maxn=2e5+; struct node
{
int d;
node* next;
}*e[maxn]; set<int>y[maxn]; //delete one
int a[maxn],x[maxn],value[maxn];
bool vis[maxn]={}; void dfs(int d)
{
set<int>::iterator i;
int dd; value[d]=x[d];
for (i=y[d].begin();i!=y[d].end();i++)
value[d]=max(value[d],*i); node* p=e[d];
vis[d]=;
while (p)
{
dd=p->d;
if (!vis[dd])
{
x[dd]=__gcd(x[d],a[dd]);
y[dd].insert(x[d]);
for (i=y[d].begin();i!=y[d].end();i++)
y[dd].insert(__gcd(a[dd],*i));
if (d==)
y[dd].insert(a[dd]);
dfs(dd);
}
p=p->next;
}
//free memory
y[d].clear();
} int main()
{
node* p;
int n,X,y,i;
scanf("%d",&n);
for (i=;i<=n;i++)
scanf("%d",&a[i]);
for (i=;i<n;i++)
{
scanf("%d%d",&X,&y);
p=(node*) malloc (sizeof(node));
p->d=y;
p->next=e[X];
e[X]=p; p=(node*) malloc (sizeof(node));
p->d=X;
p->next=e[y];
e[y]=p;
} x[]=a[];
dfs(); for (i=;i<n;i++)
printf("%d ",value[i]);
printf("%d",value[i]);
return ;
}
/*
3
6 10 12
1 2
2 3
*/