【Codeforces 1088 E. Ehab and a component choosing problem】 dfs

题意 给你一棵树 叫你选出k个不重叠的联通快 使得这些联通快的和除以k最大

这题和后来CF一道A题求平均数思路一样 就是找到一个最大的联通快 然后找有多少个联通快等于这个联通快 因为不能重叠 所以统计的时候要强制归零

/*
    if you can't see the repay
    Why not just work step by step
    rubbish is relaxed
    to ljq
*/
#include <cstdio>
#include <cstring>
#include <iostream>
#include <queue>
#include <cmath>
#include <map>
#include <stack>
#include <set>
#include <sstream>
#include <vector>
#include <stdlib.h>
#include <algorithm>
using namespace std;

#define dbg(x) cout<<#x<<" = "<< (x)<< endl
#define dbg2(x1,x2) cout<<#x1<<" = "<<x1<<" "<<#x2<<" = "<<x2<<endl
#define dbg3(x1,x2,x3) cout<<#x1<<" = "<<x1<<" "<<#x2<<" = "<<x2<<" "<<#x3<<" = "<<x3<<endl
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))

typedef pair<int,int> pll;
typedef long long ll;
const int inf = 0x3f3f3f3f;
const int _inf = 0xc0c0c0c0;
const ll INF = 0x3f3f3f3f3f3f3f3f;
const ll _INF = 0xc0c0c0c0c0c0c0c0;
const ll mod =  (int)1e9+7;

ll gcd(ll a,ll b){return b?gcd(b,a%b):a;}
ll ksm(ll a,ll b,ll mod){int ans=1;while(b){if(b&1) ans=(ans*a)%mod;a=(a*a)%mod;b>>=1;}return ans;}
ll inv2(ll a,ll mod){return ksm(a,mod-2,mod);}
const int MAX_N = 300025;
vector<int > G[MAX_N];
long long ans,dp[MAX_N],dp_[MAX_N],ANS,arr[MAX_N];
void dfs(int rt,int fa)
{
    dp[rt] = arr[rt];
    int sz = G[rt].size();
    for(int i = 0;i<sz;++i)
    {
        int to = G[rt][i];
        if(to == fa) continue;
        dfs(to,rt);
        if(dp[to]>0) dp[rt]+=dp[to];
    }
    ans = max(ans,dp[rt]);
    return ;
}
void dfs_(int rt,int fa)
{
    dp_[rt] = arr[rt];
    int sz = G[rt].size();
    for(int i = 0;i<sz;++i)
    {
        int to = G[rt][i];
        if(to == fa) continue;
        dfs_(to,rt);
        if(dp_[to]>0) dp_[rt]+=dp_[to];
    }
    if(dp_[rt]==ans) ANS++,dp_[rt] = 0;
    return ;
}
int main()
{
    //ios::sync_with_stdio(false);
    //freopen("a.txt","r",stdin);
    //freopen("b.txt","w",stdout);
    ans = _INF;
    int n;
    scanf("%d",&n);
    for(int i = 1;i<=n;++i) scanf("%lld",&arr[i]);
    for(int i = 1;i<n;++i)
    {
        int a,b;
        scanf("%d%d",&a,&b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
    dfs(1,0);
    dfs_(1,0);
    printf("%lld %lld\n",ans*ANS,ANS);
    //fclose(stdin);
    //fclose(stdout);
    //cout << "time: " << (long long)clock() * 1000 / CLOCKS_PER_SEC << " ms" << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/heucodesong/article/details/88719690