洛谷 P2370 yyy2015c01的U盘

题目传送门

解题思路:

先将每个文件按照占空间从小到大排序,然后跑背包,当到了某一个文件时,价值够了,那么当前文件的体积就是答案.

其实本题是可以二分答案的,但是写挂了...

AC代码:

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 
 5 using namespace std;
 6 
 7 int n,s,p,f[1001];
 8 struct kkk{
 9     int w,c;
10 }e[1001];
11 
12 inline bool cmp(kkk a,kkk b) {
13     return a.w < b.w;
14 }
15 
16 int main() {
17     scanf("%d%d%d",&n,&s,&p);
18     for(int i = 1;i <= n; i++)
19         scanf("%d%d",&e[i].w,&e[i].c);
20     sort(e+1,e+1+n,cmp);
21     for(int i = 1;i <= n; i++) {
22         for(int j = p;j >= e[i].w; j--)
23             f[j] = max(f[j],f[j-e[i].w] + e[i].c);
24         if(f[p] >= s) {
25             printf("%d",e[i].w);
26             return 0;
27         }
28     }
29     printf("No Solution!");
30     return 0;
31 }
原文地址:https://www.cnblogs.com/lipeiyi520/p/12301929.html