开心的金明 深搜

来源:互联网 发布:夜访吸血鬼 结局 知乎 编辑:程序博客网 时间:2024/05/16 17:54

http://ayit.acmclub.com/index.php?app=problem_title&id=233&problem_id=21496

最经典的背包为题,很不幸的我在尝试DFS 的时候阵亡了。。。。。。。。

在YYYL 的帮助下,我重新认识了DFS 。

#include <iostream>#include<cstdio>#include <algorithm>#include <functional>#include <vector>using namespace std;int maxx ,N,m;struct  A{    int a,b;}c[30];void dfs(int x,int y,int sum){    if(x > m || y > N) return ;    if(sum>maxx)    maxx = sum;    dfs(x+1,y+ c[x].a,sum +c[x].a*c[x].b);    dfs(x+1,y,sum);}int main(){    //freopen("2.txt","w",stdout);    cin>>N>>m;    maxx = -100000000;    for(int i = 0; i < m; i++)    cin>>c[i].a>>c[i].b;    c[m].a = c[m].b = 0;    dfs(0,0,0);    //cout<<dfs(0, 0,0)<<endl;    cout<<maxx<<endl;    return 0;}
更为简洁的一种,直接在DFS 中用return  ;

#include <iostream>#include<cstdio>#include <algorithm>#include <functional>#include <vector>using namespace std;int maxx ,N,m;struct  A{    int a,b;}c[30];int dfs(int x,int y){    if(x > m || y > N) return -c[x-1].a*c[x-1].b;    return max(dfs(x+1, y), dfs(x+1, y + c[x].a) + c[x].a*c[x].b);}int main(){    //freopen("2.txt","w",stdout);    cin>>N>>m;    maxx = -100000000;    for(int i = 0; i < m; i++)    cin>>c[i].a>>c[i].b;    c[m].a = c[m].b = 0;    cout<<dfs(0, 0)<<endl;    //cout<<maxx<<endl;    return 0;}



0 0
原创粉丝点击