51nod 1351 吃点心(贪心)

本文介绍了一道NOI题目,通过两种策略解决区间选择问题:按low值或high值排序。提供了完整的C++代码实现,并解释了判断条件确保所选区间的low值总和或剩余未选high值总和大于等于x。

 http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1351

题意:

 

思路:

要么先选low值大的,要么先选high值大的,分两种情况讨论。

每次只要选了的low值和>=x或者c-未选的high值和>=x就肯定满足了。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<queue>
 5 #include<algorithm>
 6 using namespace std;
 7 const int maxn = 50+5;
 8 
 9 int n,c,x,lowtot,hightot;
10 
11 struct node
12 {
13     int low,high;
14     bool operator< (const node& rhs) const
15     {
16         return low > rhs.low;
17     }
18 }a[maxn];
19 
20 bool cmp(node a, node b)
21 {
22     return a.high>b.high;
23 }
24 
25 int main()
26 {
27     //freopen("in.txt","r",stdin);
28     int T;
29     scanf("%d",&T);
30     while(T--)
31     {
32         lowtot = hightot = 0;
33         scanf("%d%d%d",&n,&c,&x);
34         for(int i=1;i<=n;i++)
35         {
36             scanf("%d%d",&a[i].low,&a[i].high);
37             lowtot += a[i].low;
38             hightot += a[i].high;
39         }
40         int sum = 0;
41         int ans = 0;
42         sort(a+1,a+n+1);
43         int tmp = hightot;
44         for(int i=1;i<=n;i++)
45         {
46             sum += a[i].low;
47             ans++;
48             hightot -= a[i].high;
49             if(sum>=x || c-hightot>=x)  break;
50         }
51 
52         sum = 0;
53         int ans2 = 0;
54         sort(a+1,a+n+1,cmp);
55         hightot = tmp;
56         for(int i=1;i<=n;i++)
57         {
58             sum += a[i].low;
59             ans2++;
60             hightot -= a[i].high;
61             if(sum>=x || c-hightot>=x)  break;
62         }
63         printf("%d\n",min(ans,ans2));
64     }
65     return 0;
66 }

 

转载于:https://www.cnblogs.com/zyb993963526/p/8039974.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值