题目:
Ahui Writes Word
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 2583 Accepted Submission(s): 937
Problem Description
We all know that English is very important, so Ahui strive for this in order to learn more English words. To know that word has its value and complexity of writing (the length of each word does not exceed 10 by only lowercase letters), Ahui wrote the complexity of the total is less than or equal to C.
Question: the maximum value Ahui can get.
Note: input words will not be the same.
Question: the maximum value Ahui can get.
Note: input words will not be the same.
Input
The first line of each test case are two integer N , C, representing the number of Ahui’s words and the total complexity of written words. (1 ≤ N ≤ 100000, 1 ≤ C ≤ 10000)
Each of the next N line are a string and two integer, representing the word, the value(Vi ) and the complexity(Ci ). (0 ≤ Vi , Ci ≤ 10)
Each of the next N line are a string and two integer, representing the word, the value(Vi ) and the complexity(Ci ). (0 ≤ Vi , Ci ≤ 10)
Output
Output the maximum value in a single line for each test case.
Sample Input
5 20 go 5 8 think 3 7 big 7 4 read 2 6 write 3 5
Sample Output
15HintInput data is huge,please use “scanf(“%s”,s)”
Author
Ahui
Source
描述:每一个单词都有它的复杂度和价值,现在给你N个单词(1~1e6)和复杂度上限C(1~1e5),再给你N的单词的价值v和复杂度c(0~10),求能组合出的不超过复杂度上限的最高价值。
题解:这题乍一看是一个01背包问题,但是时间复杂度是o(N*C)肯定会T,注意到价值和复杂度的组合数一共只有121种,而会给我们1e6个单词,那么一定会有重复的,于是我们要合并重复的之后,每一种单词有一定数量,这就转化成了多重背包问题,在具体求解时,针对每一种单词,如果数量乘以复杂度超过了复杂度上限,那么这种单词就当作完全背包来做(相当于数量没有上限),而不足的就是01背包,而且01背包还可以用二进制来优化拆分,会更快。dp[i]表示装入容量为i的背包可以获得的最大价值(不一定装满),最后输出dp[C]即可。
代码:
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
using namespace std;
const int maxn = 126;
int dp[10005], v[maxn], w[maxn], c[maxn];
int C;
struct word
{
int v;
int w;
bool operator< (const word b)
{
return w < b.w || (w == b.w && v < b.v);
}
bool operator == (const word b)
{
return v == b.v && w == b.w;
}
}wo[100005];
void zero_one_pack(int v, int w)
{
for (int i = C; i >= w; i--)
dp[i] = max(dp[i], dp[i - w] + v);
}
void complete_pack(int v, int w)
{
for (int i = w; i <= C; i++)
dp[i] = max(dp[i], dp[i - w] + v);
}
void multi_pack(int v, int w, int c)
{
if (c*w >= C)
{
complete_pack(v, w);
}
else
{
int k = 1;
while (k < c)
{
zero_one_pack(v*k, w*k);
c -= k;
k *= 2;
}
zero_one_pack(c*v, c*w);
}
return;
}
int main()
{
//freopen("input.txt", "r", stdin);
int N;
char s[20];
while (scanf("%d%d", &N, &C) ==2)
{
memset(dp, 0, sizeof(dp));
for (int i = 0; i < N; i++)
{
scanf("%s %d%d", s, &wo[i].v, &wo[i].w);
}
sort(wo, wo + N);
int num = 0; //计算种数
w[0] = wo[0].w;
v[0] = wo[0].v;
c[0] = 1;
for (int i = 1; i < N; i++) //合并
{
if (wo[i] == wo[i-1])
{
c[num]++;
}
else
{
num++;
v[num] = wo[i].v;
w[num] = wo[i].w;
c[num] = 1;
}
}
for (int i = 0;i <= num; i++)
{
multi_pack(v[i], w[i], c[i]);
}
printf("%d\n", dp[C]);
}
return 0;
}