其他分享
首页 > 其他分享> > D. Choosing Capital for Treeland(思维+换根dp)

D. Choosing Capital for Treeland(思维+换根dp)

作者:互联网

https://codeforces.com/problemset/problem/219/D


思路:

n^2暴力dfs好写吧。

好写那就改成换根dp。

先dp[u]跑以u为根的子树结果。

再dfs一遍以u为根到整棵树的结果

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<cmath>
#include<map>
#include<set>
#include<cstdio>
#include<algorithm>
#define debug(a) cout<<#a<<"="<<a<<endl;
using namespace std;
const int maxn=2e5+1000;
typedef long long LL;
inline LL read(){LL x=0,f=1;char ch=getchar();	while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}while (isdigit(ch)){x=x*10+ch-48;ch=getchar();}
return x*f;}
vector<LL>g[maxn];
multiset<LL>s[maxn];
LL dp[maxn];
void predfs(LL u,LL fa){
     dp[u]=0;
     for(LL i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==fa) continue;
        predfs(v,u);
        if(s[u].find(v)==s[u].end()) dp[u]+=dp[v]+1;
        else dp[u]+=dp[v];
     }
}
void dfs(LL u,LL fa){

     for(LL i=0;i<g[u].size();i++){
        LL v=g[u][i];
        if(v==fa) continue;
        dp[v]=dp[u];
        if(s[u].find(v)!=s[u].end() ) dp[v]++;
        else dp[v]--;
        dfs(v,u);
     }
}
int main(void)
{
  cin.tie(0);std::ios::sync_with_stdio(false);
  LL n;cin>>n;
  for(LL i=1;i<n;i++){
    LL u,v;cin>>u>>v;
    g[u].push_back(v);
    g[v].push_back(u);
    s[u].insert(v);
  }
  predfs(1,0);
  dfs(1,0);
  LL mx=1e18;
  for(LL i=1;i<=n;i++){
    mx=min(mx,dp[i]);
  }
  vector<LL>v;
  for(LL i=1;i<=n;i++){
    if(dp[i]==mx){
        v.push_back(i);
    }
  }
  cout<<mx<<"\n";
  for(auto i:v){
    cout<<i<<" ";
  }
  cout<<"\n";
return 0;
}

 

标签:Treeland,LL,back,dfs,maxn,Choosing,Capital,include,dp
来源: https://blog.csdn.net/zstuyyyyccccbbbb/article/details/114701322