思路:
从1出发进行搜索,然后儿子节点返回时统计值就好了,画一个大一点的树就能找到所有的情况了。
4种情况:
1.叶子节点,通过边1来访问,return 0;
2.叶子节点,通过边2来访问,return 1;
3.非叶子节点,通过边2来访问而且他的孩子统计为0(他的孩子都不需要加到集合里面),return 1;
4.非叶子节点,其他情况return 0。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 200005
#define MAXN 200005
#define mod 1000000007
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 0.000001
typedef long long ll;
using namespace std;
int n,m,ans,cnt,cxx;
int pp[maxn],vis[maxn],a[maxn];
struct Node
{
int v,next;
int k;
} edge[maxn];
void addedge(int u,int v,int k)
{
cnt++;
edge[cnt].v=v;
edge[cnt].k=k;
edge[cnt].next=pp[u];
pp[u]=cnt;
}
int dfs(int u,int k)
{
int i,j,v,t,flag=0,res=0;
for(i=pp[u]; i; i=edge[i].next)
{
v=edge[i].v;
if(!vis[v])
{
vis[v]=1;
flag=1;
res+=dfs(v,edge[i].k);
}
}
if(!flag)
{
if(k==2)
{
a[++cxx]=u;
return 1;
}
return 0;
}
if(res==0&&k==2)
{
a[++cxx]=u;
return 1;
}
return res;
}
int main()
{
int i,j,t,x,y;
while(~scanf("%d",&n))
{
cnt=cxx=0;
memset(pp,0,sizeof(pp));
for(i=1; i<n; i++)
{
scanf("%d%d%d",&x,&y,&t);
addedge(x,y,t);
addedge(y,x,t);
}
memset(vis,0,sizeof(vis));
vis[1]=1;
ans=dfs(1,1);
printf("%d\n",ans);
if(ans)
{
for(i=1; i<ans; i++)
{
printf("%d ",a[i]);
}
printf("%d\n",a[i]);
}
}
return 0;
}