题意:
给一颗树,每条边给定一个方向,沿着改方向代价为0,逆向走代价为1。问从一个点可以到达其他所有点的最小代价,和能达到最小代价的点。
思路:
因为是树,两个点之间有且仅有一个简单路径。容易发现,相邻的两个点付出的代价一定相差1。
所以第一次dfs处理出一个点的代价,然后由这个点在树上依次推出其他点的代价,最后统计一下。
代码:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <map>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <sstream>
#define pb push_back
#define X first
#define Y second
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define pii pair<int,int>
#define qclear(a) while(!a.empty())a.pop();
#define lowbit(x) (x&-x)
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define mst(a,b) memset(a,b,sizeof(a))
#define cout3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl
#define cout2(x,y) cout<<x<<" "<<y<<endl
#define cout1(x) cout<<x<<endl
#define IOS std::ios::sync_with_stdio(false)
#define SRAND srand((unsigned int)(time(0)))
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
using namespace std;
const double PI=acos(-1.0);
const int INF=0x3f3f3f3f;
const ll INFF=0x3f3f3f3f3f3f3f3f;
const ull mod=212370440130137957;
const double eps=1e-5;
const int maxn=200005;
const int maxm=20005;
const int base=31;
int n;
vector<pii>maps[maxn];
bool vis[maxn];
int dfs1(int u){
vis[u]=1;
int ret=0;
for(int i=0;i<maps[u].size();i++){
int now=maps[u][i].X;
if(vis[now])continue;
ret+=maps[u][i].Y+dfs1(now);
}
return ret;
}
int dp[maxn];
void dfs2(int u){
vis[u]=1;
for(int i=0;i<maps[u].size();i++){
int now=maps[u][i].X;
if(vis[now])continue;
if(maps[u][i].Y)dp[now]=dp[u]-1;
else dp[now]=dp[u]+1;
dfs2(now);
}
}
void solve() {
sd(n);
for(int i=1;i<n;i++){
int u,v;
sdd(u,v);
maps[u].pb(make_pair(v,0));
maps[v].pb(make_pair(u,1));
}
mst(vis,0);
dp[1]=dfs1(1);
mst(vis,0);
dfs2(1);
int ans=INF;
for(int i=1;i<=n;i++){
ans=min(ans,dp[i]);
}
printf("%d\n",ans);
for(int i=1;i<=n;i++){
if(dp[i]==ans){
printf("%d ",i);
}
}
printf("\n");
return ;
}
int main() {
#ifdef LOCAL
freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
#else
// freopen("","r",stdin);
// freopen("","w",stdout);
#endif
solve();
return 0;
}