1053. Path of Equal Weight

题目链接:http://pat.zju.edu.cn/contests/pat-a-practise/1053

同一类型:路径长度、保存与给定值相同的路径长度、记录一定深度的路径、记录节点号/值。

// 采用邻接表表示树
// 用vector存储路径
// 路径不止1一条,需用vector< vector<int> >存储所有路径

// 输入时建树
// 得到一个节点的所有子节点后,进行排序:按权值
// dfs遍历,叶节点处判断。返回上一层时,去掉path中的权值



#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <ctype.h>
#include <limits.h>

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <map>
#include <set>

#define SIZE 100+10

using namespace std;


struct Node
{
	int key;
	vector<int> child;
};

int N, M, S;
vector<Node> Tree;
vector<int> path;
vector<vector<int> > ans;

bool cmp(int a, int b)
{
	return Tree[a].key > Tree[b].key;
}

void Input()
{
	scanf("%d%d%d", &N, &M, &S);
	int i;
	for(i = 0; i < N; i++)
	{
		Node t;
		scanf("%d", &t.key);
		Tree.push_back(t);
	}

	// input and creating tree
	for(i = 0; i < M; i++)
	{
		int id, num;
		scanf("%d%d", &id, &num);
		while(num-- > 0)
		{
			int child_id;
			scanf("%d", &child_id);
			Tree[id].child.push_back(child_id);
		}

		//sorting
		sort(Tree[id].child.begin(), Tree[id].child.end(), cmp);
	}
	return ;
}

void dfs(int id, int sum)
{
	path.push_back(Tree[id].key);
	sum = sum + Tree[id].key;

	// leaf
	if(Tree[id].child.size() == 0)
	{
		if(sum == S)
		{
			ans.push_back(path);	
			return ;
		}// 得到一条路径
		else
		{

			return ;
		}
	}
	else
	{
		if(sum < S)
		{
			for(int j=0; j<Tree[id].child.size(); j++)
			{
				int next = Tree[id].child[j];
				dfs(next, sum);
				path.pop_back();//当前节点退出路径
			}
			return ;//所有子节点遍历完成,返回
		}
		else
		{
			return ;//非叶节点的和已经大于等于S,返回
		}
	}
}

// 构造树后输出结果,验证是否正确
void Output()
{
	for(int i=0; i < Tree.size(); i++)
	{
		printf("%02d:", i);
		for(int j=0; j<Tree[i].child.size(); j++)
		{
			printf("%d ", Tree[i].child[j]);
		}
		printf("\n");
	}
}

int main()
{
	#ifdef ONLINE_JUDGE
	#else
		freopen("E:\\in.txt", "r", stdin);
	#endif

	Input();
//	Output();

	int sum = 0;
	dfs(0, sum);

	// output
	for(int i=0; i < ans.size(); i++)
	{
		for(int j=0; j<ans[i].size()-1; j++)
		{
			printf("%d ", ans[i][j]);
		}
		printf("%d\n", ans[i][ans[i].size()-1]);
	}
	return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值