洛谷P478背包问题与贪心

参考:1.https://www.cnblogs.com/A-S-KirigiriKyoko/p/6036368.html
2.https://blog.csdn.net/u014296502/article/details/80015722
3.https://www.cnblogs.com/Christal-R/p/Dynamic_programming.html
4.https://blog.csdn.net/chanmufeng/article/details/82955730
早起写代码2:00 6:00就醒了QAQ
在这里插入图片描述
首先背包(自己写的)

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

int dp[5000][5000] = { 0 };

int main()
{
    int n, s, a, b;
    cin >> n >> s >> a >> b;
    int apple[5000] = { 0 };
    int num = 0;
    int xi, yi;
    for (int i = 0; i < n; ++i)
    {
        cin >> xi >> yi;
        if (a + b >= xi)
        {
            num++;
            apple[num] = yi;//之前先赋值再num++,导致wa,记住这是apple对应编号的属性,
            所以从1开始有意义,错了很多次了!!!!
        }
    }
    int i = 1;
    int j = 1;
    for (i = 1; i <= num; i++)
    {
        for (j = 1; j <= s; j++)
        {
            if (apple[i] > j)
            {
                dp[i][j] = dp[i - 1][j];
            }
            else
            {
                dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - apple[i]] + 1);
            }
        }
    }
    cout << dp[num][s];
    return 0;
}

再来贪心 快排模板抄的日后研究

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


void Qsort(int arr[], int low, int high)
{
    if (high <= low) return;
    int i = low;
    int j = high + 1;
    int key = arr[low];
    while (true)
    {
        while (arr[++i] < key)
        {
            if (i == high){
                break;
            }
        }
        while (arr[--j] > key)
        {
            if (j == low){
                break;
            }
        }
        if (i >= j) break;
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    int temp = arr[low];
    arr[low] = arr[j];
    arr[j] = temp;
    Qsort(arr, low, j - 1);
    Qsort(arr, j + 1, high);
}

int main()
{
    int n, s, a, b;
    cin >> n >> s >> a >> b;
    int apple[5000] = { 0 };
    int num = 0;
    int xi, yi;
    for (int i = 0; i < n; ++i)
    {
        cin >> xi >> yi;
        if (a + b >= xi)
        {
            apple[num] = yi;
            num++;
        }
    }
    Qsort(apple, 0, num - 1);
    int ans = 0;
    int sum = 0;
    for (int i = 0; i < num; ++i)
    {
        sum += apple[i];
        if (sum > s)
        {
            break;
        }
        ans++;
    }
    cout << ans;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值