D. Choosing Capital for Treeland(树形dp

#include<bits/stdc++.h>
using namespace std;
const int mod=1000000007;
const int N=4e5+10;
struct node{
    int to,nxt,val;
}d[N];int head[N],tot=0;
void add(int a,int b,int val){
    d[++tot]={b,head[a],val};head[a]=tot;
}
int f[N],pos=0,MIN=1e9;
vector<int> v;
void dfs(int x,int fa,int val){
    for(int i=head[x];i;i=d[i].nxt){
        int to=d[i].to;if(to==fa) continue;
        dfs(to,x,val+d[i].val);
        f[x]+=f[to]+(d[i].val==-1);
    }
    if(MIN>val){
        MIN=val;pos=x;
        v.clear();v.push_back(x);
    }else if(MIN==val){
        v.push_back(x);
    }
}
int n;
int main(){
    while(scanf("%d",&n)!=EOF){
        tot=0;pos=0;MIN=1e9;
        memset(head,0,sizeof head);
        memset(f,0,sizeof f);
        for(int i=1;i<n;i++){
            int v,u;scanf("%d%d",&u,&v);
            add(u,v,1);add(v,u,-1);
        }
        dfs(1,0,0);
//        cout<<f[1]<<endl;
        cout<<MIN+f[1]<<endl;
        sort(v.begin(),v.end());
        for(auto it:v){
            cout<<it<<" ";
        }cout<<endl;
        v.clear();
    }


}

上一篇:python测试开发django-16.JsonResponse返回中文编码问题


下一篇:CF264C Choosing Balls