深度优先搜索应用题(算法笔记例题)

360 篇文章 3 订阅
88 篇文章 5 订阅

在这里插入图片描述

#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set> 
#include<unordered_map> 
#include<fstream>
using namespace std;
int n,v,maxvalue=0;//此时要定义全局变量,因为在Dfs调用的时候需要使用
const int maxn=21;
int w[maxn],c[maxn]; 
void Dfs(int index,int sumw,int sumc){
	if(index==n){//如果index==n,意思是全都选完了
		if(sumw<=v&&sumc>maxvalue){//判断是否满足条件以及是否是最大的maxvalue
			maxvalue=sumc;
		}
		return ;
	}
	Dfs(index+1,sumw+w[index],sumc+c[index]);//选该物品 ,index加一,重量和价值都加上该物品
	Dfs(index+1,sumw,sumc);//不选该物品 ,只让index加
}
int main(){
	cin>>n>>v;//输入n与v
	for(int i=0;i<n;i++){
		cin>>w[i];
	}
	for(int i=0;i<n;i++){
		cin>>c[i];
	}
	Dfs(0,0,0);//从第0个物品开始,重量是0,价值是0
	cout<<maxvalue;
}


在这里插入图片描述

#include <iostream>
#include <string>
#include<algorithm>
#include<bits/stdc++.h>
#include<stack>
#include<set>
#include <vector>
#include <map>
#include<queue>
#include<deque>
#include<cctype>
#include<unordered_set> 
#include<unordered_map> 
#include<fstream>
using namespace std;
int n,k,x,nowk,maxpf=0,sumx=0,maxnow;
const int maxn=1001;
int a[maxn];
vector<int>temp,ans;
void Dfs(int index,int nowk,int sumx,int maxnow){
	if(nowk==k&&sumx==x){//如果此时满足条件,找到了
		if(maxnow>maxpf){//判断是不是最优解
			maxpf=maxnow;//是最优解赋值
			temp=ans;//记录最优解的值
		} 
		return ;
	}
	if(index==n||nowk>k||sumx>x) return ;//不满足条件,直接返回
	//选择
	ans.push_back(a[index]);//选择,将该数放入数组
	Dfs(index+1,nowk+1,sumx+a[index],maxnow+a[index]*a[index]);//选择该数,index加一,nowk加1,等
	ans.pop_back();//没选上,放出
	//不选择 
	Dfs(index+1,nowk,sumx,maxnow); 
}
int main(){
	cin>>n>>k>>x;
	for(int i=0;i<n;i++){
		cin>>a[i];
	}
	Dfs(0,0,0,0);//第0个数,此时k=0,sumx=0,最大也为0
	for(int i=0;i<temp.size();i++){
		cout<<temp[i]<<" ";
	}
	cout<<endl<<maxpf;
}


如果每个数可以多次选择,那么只需要修改一个语句

Dfs(index,nowk+1,sumx+a[index],maxnow+a[index]*a[index]);//这里index不加一,继续用该数
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_努力努力再努力_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值