PAT 1053

题目

红色线
Sample Input:

20 9 24
10 2 4 3 5 10 2 18 9 7 2 2 1 3 12 1 8 6 2 2
00 4 01 02 03 04
02 1 05
04 2 06 07
03 3 11 12 13
06 1 09
07 2 08 10
16 1 15
13 3 14 16 17
17 2 18 19

Sample Output:

10 5 2 7
10 4 10
10 3 3 6 2
10 3 3 6 2

给定一个目标值target, 要求从根节点到叶子结点的所有权值和为target值,如果有多条路径,则从大到小输出(这里指的是从大到小指的是比较两个路径,要求输出权值较大的的那个,例如 10-4-3和10-3-4先输出第一个)

代码和思路

  1. 本身就是对数的遍历,用静态链表就可以,使用二维vector数组
  2. 本身代码和之前图DFS很相似
  3. 遍历得到所有的路径不难,主要是对输出的顺序的处理
  4. 建议在一开始的时候就将节点的值按照权值排好,这样就简单一点。。
  5. DFS并不难,就是一个标准的模板
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 101;

int weight[maxn];
int tar, n, path;
vector<int> node[maxn];
vector<int> getpath[maxn];
vector<int> tempPath;
int num = 0;
int flag = 0;

bool cmp(int a, int b) {
	return weight[a] > weight[b];
}

int DFS(int x) {
	tempPath.push_back(x);
	if (node[x].empty()) {
		int ans = 0;
		for (int i = 0; i < tempPath.size(); i++) {
			ans += weight[tempPath[i]];
		}
		if (ans == tar) {
			getpath[flag++] = tempPath;
			num++;
		}
		tempPath.pop_back();
		return 0;
	}
	for (int i = 0; i < node[x].size(); i++) {
		DFS(node[x][i]);
	}
	tempPath.pop_back();
	return 0;
}

int main() {
	int ans = 0;
	int id;
	scanf("%d %d %d", &n, &path, &tar);
	for (int i = 0; i < n; i++) {
		scanf("%d", &weight[i]);
	}
	for (int i = 0; i < path; i++) {
		int pathnum, cur;
		scanf("%d %d", &cur, &pathnum);
		for (int j = 0; j < pathnum; j++) {
			scanf("%d", &id);
			node[cur].push_back(id);
		}
		sort(node[cur].begin(), node[cur].end(), cmp);
	}
	DFS(0);
	for (int i = 0; i < num; i++) {
		for (int j = 0; j < getpath[i].size(); j++) {
			getpath[i][j] = weight[getpath[i][j]];
		}
	}
	for (int i = 0; i < num; i++) {
		for (int j = 0; j < getpath[i].size(); j++) {
			printf("%d", getpath[i][j]);
			if (j != getpath[i].size() - 1) printf(" ");
		}
		printf("\n");
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值