开心的金明 深搜

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;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值