The country Treeland consists of n cities, some pairs of them are connected with unidirectional roads. Overall there are n - 1 roads in the country. We know that if we don't take the direction of the roads into consideration, we can get from any city to any other one.
The council of the elders has recently decided to choose the capital of Treeland. Of course it should be a city of this country. The council is supposed to meet in the capital and regularly move from the capital to other cities (at this stage nobody is thinking about getting back to the capital from these cities). For that reason if city a is chosen a capital, then all roads must be oriented so that if we move along them, we can get from city a to any other city. For that some roads may have to be inversed.
Help the elders to choose the capital so that they have to inverse the minimum number of roads in the country.
InputThe first input line contains integer n (2 ≤ n ≤ 2·105) — the number of cities in Treeland. Next n - 1 lines contain the descriptions of the roads, one road per line. A road is described by a pair of integers si, ti (1 ≤ si, ti ≤ n; si ≠ ti) — the numbers of cities, connected by that road. The i-th road is oriented from city si to city ti. You can consider cities in Treeland indexed from 1 to n.
OutputIn the first line print the minimum number of roads to be inversed if the capital is chosen optimally. In the second line print all possible ways to choose the capital — a sequence of indexes of cities in the increasing order.
Examples Input 3 2 1 2 3 Output 0 2 Input 4 1 4 2 4 3 4 Output 2 1 2 3题意:有n个点,n-1条单向边,如果选择其中一个点作为root,那么从这个点到其他所有点(不返回)需要改变一些单向边才能到达,问你合适的选择root点使改变的单向边数目最少,输出最少数目和这些合适的root点。
分析:考虑到单向边u->v,我们可以建边(u,v,0)和(v,u,1),费用为1就代表需要改变这条边方向,还是很巧妙的。对于答案跑两次dfs即可解决。
#include<bits/stdc++.h> using namespace std; #define maxn 200010 #define inf 1e8 int p[maxn],num; struct node { int u,v,len,next; node() {} node(int u,int v,int len,int next): u(u),v(v),len(len),next(next) {} } E[maxn*2]; void init() { num=0; memset(p,-1,sizeof(p)); } void add(int u,int v,int len) { E[num]=node(u,v,len,p[u]); p[u]=num++; } int down[maxn]; void dfs1(int u,int fa) { for(int i=p[u];~i;i=E[i].next) { int v=E[i].v; int len1=E[i].len; int len2=E[i^1].len; if(v==fa) continue; dfs1(v,u); down[u]+=down[v]+len1; } } int ans[maxn],val[maxn]; void dfs2(int u,int fa,int len,int fa_len) { ans[u]=fa_len+len+down[u]+val[fa]; val[u]+=val[fa]+fa_len+len; for(int i=p[u];~i;i=E[i].next) { int v=E[i].v; int len1=E[i].len; int len2=E[i^1].len; if(v==fa) continue; int flen=down[u]-down[v]-len1; dfs2(v,u,len2,flen); } } int main() { int n; while(scanf("%d",&n)==1) { init(); for(int i=1;i<n;i++) { int u,v; scanf("%d%d",&u,&v); add(u,v,0); add(v,u,1); } for(int i=0;i<=n;i++) down[i]=val[i]=0; dfs1(1,0); dfs2(1,0,0,0); int minn=inf; for(int i=1;i<=n;i++) if(ans[i]<minn) minn=ans[i]; printf("%d\n",minn); for(int i=1;i<=n;i++) if(ans[i]==minn) printf("%d ",i); puts(""); } return 0; }
