参考: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;
}