The city Valera lives in is going to hold elections to the city Parliament.The city has n districts and n - 1 bidirectional roads. We know that from any district there is a path along the roads to any other district. Let's enumerate all districts in some way by integers from 1 to n, inclusive. Furthermore, for each road the residents decided if it is the problem road or not. A problem road is a road that needs to be repaired.
题解:有n个节点n-1条边。题意保证所给的图是一棵树。x,y表示x到y的路线。t==2表示这条路是坏的,t==1表示这条路没有坏。当选一块区域修路时,会把从该块区域到1号区域所经过的道路全部修好。问最少可以从几个区域开始修使得全部坏的路修好。
这个dfs写法非常巧妙。
#include<cstdlib>
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<vector>
#define maxn 100010
using namespace std;
vector<int>a[maxn],ans;
int n;
void dfs(int rt,int x,int z)
{
int y,tmp,k;
tmp=ans.size();
for(int i=0;i<a[x].size();i++)
{
y=a[x][i];
if(y<0)
{
y=y*-1;
k=2;
}
else
k=1;
if(y==rt)
continue;
dfs(x,y,k);
}
if(z==2&&ans.size()==tmp)
ans.push_back(x);
}
int main()
{
int x,y,t;
while(cin>>n)
{
ans.clear();
a[maxn].clear();
for(int i=0;i<n-1;i++)
{
cin>>x>>y>>t;
a[x].push_back(y*(3-2*t));
a[y].push_back(x*(3-2*t));
}
dfs(0,1,1);
cout<<ans.size()<<endl;
for(int i=0;i<ans.size();i++)
{
if(i==0)
cout<<ans[i];
else
cout<<" "<<ans[i];
}
cout<<endl;
}
}