首页 > 其他 > 详细

BZOJ 3433 [Usaco2014 Jan]Recording the Moolympics:贪心

时间:2017-10-18 01:20:40      阅读:271      评论:0      收藏:0      [点我收藏+]

题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=3433

题意:

  给出n个区间[a,b)。

  有两个记录器,每个记录器中存放的区间不能重叠。

  求两个记录器中最多可放多少个区间。

 

题解:

  贪心。

 

  先按右端点从小到大排序。

  p1,p2分别为两个记录器的最右端。

 

  始终令p1 < p2(避免出现大材小用)。

  对于每个区间s:

    if p1 <= s.l,则将s放入p1所在记录器。即:p1 = s.r, ans++;

    else if p2 <= s.l,则将s放入p1所在记录器。即:p2 = s.r, ans++;

    else 那就没法放了...

 

AC Code:

 1 #include <iostream>
 2 #include <stdio.h>
 3 #include <string.h>
 4 #include <algorithm>
 5 #define MAX_N 155
 6 #define INF 1000000000
 7 
 8 using namespace std;
 9 
10 struct Sec
11 {
12     int l;
13     int r;
14     Sec(int _l,int _r)
15     {
16         l=_l;
17         r=_r;
18     }
19     Sec(){}
20     friend bool operator < (const Sec &a,const Sec &b)
21     {
22         return a.r!=b.r?a.r<b.r:a.l<b.l;
23     }
24 };
25 
26 int n;
27 int ans=0;
28 Sec s[MAX_N];
29 
30 void read()
31 {
32     cin>>n;
33     for(int i=0;i<n;i++)
34     {
35         cin>>s[i].l>>s[i].r;
36     }
37 }
38 
39 void solve()
40 {
41     sort(s,s+n);
42     int p1=-INF;
43     int p2=-INF;
44     for(int i=0;i<n;i++)
45     {
46         if(p1<p2) swap(p1,p2);
47         if(p1<=s[i].l)
48         {
49             ans++;
50             p1=s[i].r;
51         }
52         else if(p2<=s[i].l)
53         {
54             ans++;
55             p2=s[i].r;
56         }
57     }
58 }
59 
60 void print()
61 {
62     cout<<ans<<endl;
63 }
64 
65 int main()
66 {
67     read();
68     solve();
69     print();
70 }

 

BZOJ 3433 [Usaco2014 Jan]Recording the Moolympics:贪心

原文:http://www.cnblogs.com/Leohh/p/7684643.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!