高数Umaru系列(9)——哈士奇
Time Limit: 1000 ms Memory Limit: 65536 KiB
Problem Description
由于高数巨养的喵星人太傲娇了,要天天吃新鲜猫粮而且还经常欺负高数巨,所以高数巨决定买几条哈士奇尝尝鲜。这天高数巨来到了二手狗市场买哈士奇,高数巨看完了所有的哈士奇,记下了每条哈士奇的价格,并根据对它们的好感程度给它们每只都赋予了一个萌值。高数现在手里有X元,她想通过购买若干条哈士奇来获得尽可能多的萌值。现在给定高数巨手里的钱X以及N条哈士奇的价格和萌值,求高数巨最多可获得多少萌值
Input
多组输入。
对于每组输入,第一行有两个整数N,X(1 < = N < = 100,1 < = X < = 1000),分别表示哈士奇的数量和高数巨的钱数
接下来的N行每行有两个整数Pi,Mi(1 < = Pi,Mi < = 100),分别表示第i条哈士奇的价格和萌值
Output
对于每组数据,输出一个整数,表示高数巨最多可以获得的萌值,每组输出占一行
Sample Input
2 100
50 20
60 40
3 100
20 55
20 35
90 95
1 10
20 50
Sample Output
40
95
0
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdio>
#include <cmath>
#define N 1100
using namespace std;
int dp[N][N];//dp[n][m]
int main()
{
int n, m;
while(cin >> n >> m)
{
memset(dp, 0, sizeof(dp));
int meng[n+1], price[n + 1];
for(int i = 1; i <= n; i++)
{
cin >> price[i] >> meng[i];
}
for(int i = 0; i <= m; i++)//初始化边界:只有第一个哈士奇时的情况
{
if(i < price[1])
{
dp[1][i] = 0;
}
else
{
dp[1][i] = meng[1];
}
}
for(int i = 1; i <= n; i++)//初始化边界:金钱数为零时的情况
{
dp[i][0] = 0;
}
for(int i = 2; i <= n; i++)
{
for(int j = 1; j <= m; j++)//j可直接从 price[i]开始,需要数组初始化为零
{
if(j - price[i] >= 0)
{
dp[i][j] = max(dp[i - 1][j - price[i]] + meng[i], dp[i - 1][j]);
}
else
{
dp[i][j] = dp[i - 1][j];
}
}
}
cout << dp[n][m] << endl;
}
return 0;
}
滚动数组版本:
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <cstdio>
#include <algorithm>
#define N 200
#define M 2000
#define INF 0x3f3f3f3f
#include <queue>
using namespace std;
int dp[M];
int price[N], meng[N];
int main()
{
ios::sync_with_stdio(false);
int n, m;
while(cin >> n >> m)
{
for(int i = 1; i <= n; i++)
{
cin >> price[i] >> meng[i];
}
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++)
{
for(int j = m; j >= price[i]; j--)
{
dp[j] = max(dp[j], dp[j - price[i]] + meng[i]);
}
}
cout << dp[m] << endl;
}
return 0;
}