10月6号 卡车

题目

  分析

   第一眼看去,,很明显的背包问题。

    但看看数据规模,于是就想到了贪心,算出性价比,排序

    有一个关键点要注意

    题目的容积只有1和2

    所以当容积是双数时,一定能装完

    但单数时呢??   

    比如  

    3 3

    1 7

    2 14

    1 9

    排序后贪心一个个加后发现会容积无法达到0

    所以为了排除这种情况

    在排序是要优先排列 容积为 2 的

  代码

   

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstdio>
 4 using namespace std;
 5 struct sb
 6 {
 7     int a,b;
 8     double c;
 9 }a[100001];
10 bool cmp(sb a,sb b)
11 {
12     if (a.c==b.c) return a.a>b.a?true:false;
13     return a.c>b.c?true:false;
14 }
15 int read()
16 {
17     int x=0;
18     int c=getchar();
19     while (c>='0'&&c<='9')
20     {
21         x=x*10+c-48;
22         c=getchar();
23     }
24     return x;
25 }
26 int main ()
27 {
28     int n,v;
29     n=read(); v=read();
30     for (int i=1;i<=n;i++)
31     {
32         a[i].a=read();
33         a[i].b=read();
34         a[i].c=a[i].b/a[i].a;
35     }
36     sort(a+1,a+1+n,cmp);
37     int ans=0;
38     int j=1;
39     while(v!=0&&j<=n)
40     {
41         if (v>=a[j].a)
42         {
43             ans+=a[j].b;
44             v-=a[j].a;
45         }
46         j++;
47     }
48     cout<<ans;
49 }

猜你喜欢

转载自www.cnblogs.com/zjzjzj/p/9747738.html