1053 Path of Equal Weight (30point(s)) Easy only once *路径权值排序思想,通过子节点权值排序,非常重要

基本思想:

路径节点权值统计,倒是不难,但是卡在了输出路径的权值排序上;

由于要求路径权值总和相等,但是里面的节点要求降序,这就不能用简单的sort来进行解决;

而是要直接把子节点进行排序,使得无论如何,先遍历的都是权值最大的,所以就可以保证在权值和想等情况下,先访问的都是大值节点;

关键点:

无;

#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<vector> 
#include<string>
#include<math.h>
#include<algorithm>
#include<cstring>
#include<map>
#include<queue>
using namespace std;

int n;
int m;
int s;

struct node {
	int w;
	vector<int>child;
};

struct pnode {
	int p;
	vector<int>pa;
};

vector<node>tree;
vector<int>path;
vector<pnode>fin;
int cnt = 0;

void find_path(int n,int s) {
	if (tree[n].child.size() == 0) {
		//如果为叶子节点;
		cnt += tree[n].w;
		path.push_back(tree[n].w);
		if (cnt == s) {
			pnode pn;
			pn.p = cnt;
			pn.pa = path;
			fin.push_back(pn);
			cnt -= tree[n].w;
			path.pop_back();
		}
		else {
			cnt -= tree[n].w;
			path.pop_back();
		}
		return;
	}
	path.push_back(tree[n].w);
	cnt += tree[n].w;
	for (int i = 0; i < tree[n].child.size(); i++) {
		find_path(tree[n].child[i], s);
	}
	path.pop_back();
	cnt -= tree[n].w;
}

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

int main() {
	cin >> n >> m >> s;
	tree.resize(n);
	for (int i = 0; i < n; i++) {
		cin >> tree[i].w;
	}
	int a, b, c;
	for (int i = 0; i < m; i++) {
		cin >> a >> b;
		for (int j = 0; j < b; j++) {
			cin >> c;
			tree[a].child.push_back(c);
		}
	}
	for (int i = 0; i < n; i++) {
		sort(tree[i].child.begin(), tree[i].child.end(), cmp);
	}
	find_path(0, s);
	for (int i = 0; i < fin.size(); i++) {
		for (int j = 0; j < fin[i].pa.size(); j++) {
			if (j == 0)
				cout << fin[i].pa[j];
			else
				cout << " " << fin[i].pa[j];
		}
		cout << endl;
	}
	return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/songlinxuan/p/12308374.html