Codeforces Round #216 (Div. 2) C - Valera and Elections(图论和dfs)

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string.h>
#include <queue>
#include <vector>
#define N 100010
using namespace std;  //Codeforces Round #216 (Div. 2)  C - Valera and Elections(图论和dfs)
vector<int> m[N];  //路是双向的,用vector来做邻接表,vetcot m[N]相当于二维矩阵
vector<int> w[N];  //w是对应上面存放路的状态,1表示好,2表示坏
int s, p[N], num[N], vis[N];   //num[x]表示x节点(相当于x为子树的根节点)以下的总共所需要的被选中的节点数
void dfs(int x)
{
	int t, k, T=m[x].size();
	vis[x]=1;
	for(t=0; t<T; ++t)
	{
		k=m[x][t];
		if(vis[k])continue;
		dfs(k);//深搜下去
		if(w[x][t]==2&&num[k]==0)  //该子节点为2且它的num值为0(表示他后面没有被选中的节点)。
		{
			p[s++]=k;
			num[x]+=1;
		}
		else num[x]+=num[k];   //累加
	}
	return ;
}
	
int main()
{
	int n, a, b, c, t;
	while(scanf("%d", &n)!=EOF)
	{
		for(t=1; t<=n; ++t)
		{
			m[t].clear();
			w[t].clear();
		}
		n--;
		memset(num, 0, sizeof(num));
		memset(vis, 0, sizeof(vis));
		for(t=0; t<n; ++t)
		{
			scanf("%d%d%d", &a, &b, &c);  //a和b之间是双向的
			m[a].push_back(b);
			w[a].push_back(c);
			m[b].push_back(a);
			w[b].push_back(c);
		}
		s=0;
		dfs(1);
		printf("%d\n", s);
		for(t=0; t<s; ++t)
			printf("%d ", p[t]);
		printf("\n");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值