I love sneakers!(分组背包变形)

xiaoxiao2021-02-28  109

I love sneakers!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 5504    Accepted Submission(s): 2260 Problem Description After months of hard working, Iserlohn finally wins awesome amount of scholarship. As a great zealot of sneakers, he decides to spend all his money on them in a sneaker store. There are several brands of sneakers that Iserlohn wants to collect, such as Air Jordan and Nike Pro. And each brand has released various products. For the reason that Iserlohn is definitely a sneaker-mania, he desires to buy at least one product for each brand. Although the fixed price of each product has been labeled, Iserlohn sets values for each of them based on his own tendency. With handsome but limited money, he wants to maximize the total value of the shoes he is going to buy. Obviously, as a collector, he won’t buy the same product twice. Now, Iserlohn needs you to help him find the best solution of his problem, which means to maximize the total value of the products he can buy.   Input Input contains multiple test cases. Each test case begins with three integers 1<=N<=100 representing the total number of products, 1 <= M<= 10000 the money Iserlohn gets, and 1<=K<=10 representing the sneaker brands. The following N lines each represents a product with three positive integers 1<=a<=k, b and c, 0<=b,c<100000, meaning the brand’s number it belongs, the labeled price, and the value of this product. Process to End Of File.   Output For each test case, print an integer which is the maximum total value of the sneakers that Iserlohn purchases. Print "Impossible" if Iserlohn's demands can’t be satisfied.   Sample Input 5 10000 3 1 4 6 2 5 7 3 4 99 1 55 77 2 44 66   Sample Output 255  

分组背包的变形,每组至少取一个,否则输出Impossible,输出最大值

切记,这个题不能状态压缩

#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> #include <vector> using namespace std; typedef long long LL; const int INF = 0x3f3f3f3f; const int maxn = 200+10; struct node{ int w,v; }nxt; int dp[20][10010]; int N,M,K; int main(){ int id; vector<node>V[20]; int ans; while(~scanf("%d %d %d",&N,&M,&K)){ for(int i = 1; i <= K; i++) V[i].clear(); for(int i = 0; i < N; i++){ scanf("%d",&id); scanf("%d %d",&nxt.w,&nxt.v); V[id].push_back(nxt); } bool flag = false; for(int i = 1; i <= K; i++) if(V[i].size() == 0){ flag = true; break; } if(flag){ puts("Impossible"); continue; } memset(dp,-INF,sizeof(dp)); memset(dp[0],0,sizeof(dp[0])); for(int i = 1; i <= K; i++){ for(int k = 0; k < V[i].size(); k++){ for(int j = M; j >= V[i][k].w; j--){ dp[i][j] = max(dp[i][j],dp[i][j-V[i][k].w]+V[i][k].v); dp[i][j] = max(dp[i][j],dp[i-1][j-V[i][k].w]+V[i][k].v); } } } ans = -INF; for(int i = 0; i <= M; i++) ans = max(ans,dp[K][i]); if(ans >= 0) printf("%d\n",ans); else puts("Impossible"); } return 0; }

转载请注明原文地址: https://www.6miu.com/read-33525.html

最新回复(0)