Choosing Capital for Treeland
time limit per test:3 seconds
memory limit per test: 256 megabytes
Description
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.
Input
The 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.
Output
In 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.
I think
树形DP
题目大意:有向图,选择一个节点遍历需要翻转的边数最小。
用f[i]表示顺着遍历方向i的子节点连边中需要翻转的边数,g[i]表示顺着父节点方向那颗树中需要翻转的边数,第一遍dfs,先向下搜再回溯计算
第二遍dfs
在存边的时候,仍然存双向边,但用标记区分一下原有边和翻转边就好了。
论树形dp的水题套路……
Code
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int sm = 2e5+20;
int n,s,minn=sm,f[sm],g[sm],hd[sm];
struct edge{
int to,nxt,p;
}e[sm*2];
int Min(int x,int y) {return x<y?x:y;}
void add(int f,int t,int a) {
e[++s].to=t;
e[s].p=a;
e[s].nxt=hd[f];
hd[f]=s;
}
void dfsa(int x,int fa) {
for(int i=hd[x];i;i=e[i].nxt) {
if(e[i].to==fa)continue;
dfsa(e[i].to,x);
f[x]+=f[e[i].to];
if(!e[i].p)++f[x];
}
}
char ch;
void read(int &x) {
x=0;ch=getchar();
while(ch>'9'||ch<'0')ch=getchar();
while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
}
void dfsb(int x,int fa,int p) {
if(fa<0)g[x]=0;
else if(p)g[x]=f[fa]-f[x]+1+g[fa];
else if(!p)g[x]=f[fa]-1-f[x]+g[fa];
for(int i=hd[x];i;i=e[i].nxt) {
if(e[i].to==fa)continue;
dfsb(e[i].to,x,e[i].p);
}
}
int main() {
read(n);
for(int i=1,x,y;i<n;++i) {
read(x);read(y);
add(x,y,1);
add(y,x,0);
}
dfsa(1,-1);
dfsb(1,-1,0);
for(int i=1;i<=n;++i)
minn=Min(minn,f[i]+g[i]);
printf("%d\n",minn);
for(int i=1;i<=n;++i)
if(f[i]+g[i]==minn)printf("%d ",i);
printf("\n");
return 0;
}