1053 Path of Equal Weight

博客提及存在另一段AC代码,但未给出更多详细信息。
#include<bits/stdc++.h>
using namespace std;
struct Node{
	int id;
	vector<int> child;
	int weight;
}node[110];
int n,m,s;
int path[110];
bool cmp(int a,int b){
	return node[a].weight>node[b].weight;
}
void dfs(int root,int nodenum,int tempvalue){
	if(tempvalue>s) return;
	if(tempvalue==s){
		if(node[root].child.size()==0){
			for(int i=0;i<nodenum;i++){
				if(i==0) cout<<node[path[i]].weight;
				else cout<<' '<<node[path[i]].weight;
			}
			cout<<endl;
		}else{
			return;
		}
	} 
	for(int i=0;i<node[root].child.size();i++){
		path[nodenum]=node[root].child[i];
		dfs(node[root].child[i],nodenum+1,tempvalue+node[node[root].child[i]].weight);
	}
}
int main()
{
	freopen("in.txt","r",stdin);
	cin>>n>>m>>s;
	for(int i=0;i<n;i++){
		int temp;cin>>temp;
		node[i].id=i;
		node[i].weight=temp;
	}
	for(int i=0;i<m;i++){
		int root,k;cin>>root>>k;
		for(int j=0;j<k;j++){
			node[root].child.resize(k);
			cin>>node[root].child[j];
		}
		sort(node[root].child.begin(),node[root].child.end(),cmp);
	}
	
	path[0]=0;
	dfs(0,1,node[0].weight);
	return 0;
}

另一段AC代码

#include<bits/stdc++.h> 
using namespace std;
const int MAXN=110;
struct Node{
	int weight;
	vector<int> child;
}node[MAXN];
int n,m,s;
vector<int> temp;
bool cmp(int a,int b){
	return node[a].weight>node[b].weight;
}
void dfs(int root,int sum){
	if(node[root].child.size()==0){
        sum=sum+node[root].weight;
        temp.push_back(node[root].weight);
		if(sum==s){
			for(int i=0;i<temp.size();i++){
				if(i==0) cout<<temp[i];
				else cout<<' '<<temp[i];
			}
			cout<<endl;
			temp.pop_back();
			return;
		}else{
			temp.pop_back();
			return;
		}
	}
	for(int i=0;i<node[root].child.size();i++){
		temp.push_back(node[root].weight);
		dfs(node[root].child[i],sum+node[root].weight);
		temp.pop_back();
	}
}
int main()
{
	freopen("in.txt","r",stdin);
	cin>>n>>m>>s;
	for(int i=0;i<n;i++){
		cin>>node[i].weight;
	}
	for(int i=0;i<m;i++){
		int root,k;cin>>root>>k;
		for(int j=0;j<k;j++){
			int temp;cin>>temp;
			node[root].child.push_back(temp);
		}
		sort(node[root].child.begin(),node[root].child.end(),cmp);
	}
	dfs(0,0);
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值