PAT (Advanced Level) 1053 Path of Equal Weight (dfs)

7 篇文章 0 订阅

 这题很简单,没有坑点。记录这题的原因是,第一次提交最后一个case报了段错误,我从上到下代码读了个遍,并不觉得哪里有问题,后来就在网上找,找到个跟我一样,在比较函数里,如果两个path相同,返回的值是true,导致了段错误。

查了下大概意思是:只有严格的大于,才应该返回true,小于和等于都归于false

详细解释:调用sort段错误问题

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;

int n,m;
long long s;
int w[105];
int leaf[105];
vector<int> graph[105];
struct Path{
	vector<int> weight;
	bool operator < (const Path &a) const{
		for(int i = 0; i < weight.size() && i < a.weight.size(); ++i){
			if(weight[i] != a.weight[i]){
				return weight[i] > a.weight[i];
			}
		}
		return false;
	}
};

vector<Path> ans;

void dfs(int v, long long sum, Path path){
	if(sum > s) return;
	if(sum == s){
		if(!leaf[v])
			ans.push_back(path);
		return;
	}
	for(int i = 0; i < graph[v].size(); ++i){
		int next = graph[v][i];
		path.weight.push_back(w[next]);
		dfs(next,sum+w[next],path);
		path.weight.pop_back();
	}
}
int main(){
	scanf("%d%d%lld",&n,&m,&s);
	for(int i = 0; i < n; ++i){
		scanf("%d",&w[i]);
	}
	int a, cnt, b;
	for(int i = 0; i < m; ++i){
		scanf("%d%d",&a,&cnt);
		leaf[a] = 1;
		for(int j = 0; j < cnt; ++j){
			scanf("%d",&b);
			graph[a].push_back(b);
		}
	}
	Path tmp;
	tmp.weight.push_back(w[0]);
	dfs(0,w[0],tmp);
	sort(ans.begin(),ans.end());
	for(int i = 0; i < ans.size(); ++i){
		for(int j = 0; j < ans[i].weight.size() - 1; ++j){
			printf("%d ",ans[i].weight[j]);
		}
		printf("%d\n",ans[i].weight.back());
	}
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值