Codeforces 842 C. Ilya And The Tree (dfs)

题目链接:Ilya And The Tree
题意有n个节点标号1~n,每个节点有一个正整数价值,这几个节点形成了一棵以节点1为根节点的树,求根节点到节点x的路径上所有节点价值的gcd(你可改变这条路径上某个节点的的价值为0,或者不做任何修改);

思路:爆搜+set去重

AcCode

#pragma GCC diagnostic error "-std=c++11"  
#include<iostream>
#include<cmath>
#include<cstdio>
#include<algorithm>
#include<string>
#include<map>
#include<vector>
#include<set>
using namespace std;
#define rep(i,a,b) for(int i=a;i<b;i++)
#define maxn 1000010
const int MOD = 1000000007;
typedef long long ll;
int a[300010];
vector<int>v[maxn];
set<int>s[maxn];
void dfs(int x,int fa,int now)
{
    for(auto p:s[fa])
        s[x].insert(__gcd(p,a[x]));//把父节点的所有完美值与a[x]的gcd放入set
    s[x].insert(now);//把x的价值改为0的完美值
    now=__gcd(now,a[x]);//不改变任何节点的价值
    s[x].insert(now);
    for(auto p:v[x])
        if(p!=fa)
            dfs(p,x,now);
}
int main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    int n;
    cin>>n;
    rep(i,1,1+n)cin>>a[i];
    rep(i,0,n-1)
    {
        int a,b;
        cin>>a>>b;
        v[a].push_back(b);
        v[b].push_back(a);
    }
    dfs(1,0,0);
    rep(i,1,n+1)
    cout<<*s[i].rbegin()<<' ';//输出s[i]的最大值
    cout<<endl;
    return 0;
}

*

猜你喜欢

转载自blog.csdn.net/reallsp/article/details/78321035