zoukankan      html  css  js  c++  java
  • BZOJ 3433 [Usaco2014 Jan]Recording the Moolympics:贪心

    题目链接: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 }
  • 相关阅读:
    JDK5后的特性整理
    正向代理与反向代理的区别与异同
    我所用过的nginx的功能
    网页端消息推送之推与拉
    在一个py脚本中调用另外一个py脚本中的类或函数
    import与from ... import ...的区别
    python 读取文件
    shell中的特殊变量IFS
    shell 重定向以及文件描述符
    shell下读取文件数据
  • 原文地址:https://www.cnblogs.com/Leohh/p/7684643.html
Copyright © 2011-2022 走看看