HDU 2037 区间相交问题系列之一

来源:互联网 发布:北京java程序员工资 编辑:程序博客网 时间:2024/06/14 02:19

这个问题可以简化成这个样子。

我们有好多个区间,让你尽可能的选出尽量多的不重复的区间。

这是贪心思想经典的区间相交问题的一种。


解决这种问题方法比较简单。

1.以右端点位基准,对区间进行排序。

2.只要下一个区间不与前面的区间相交,就要着,否则就不要。

3.维护一个界限。


要具体的解释的话,找找别人的博客吧~

ac代码如下

#include <iostream>#include <cstdio>#include <cstring>#include <set>#include <queue>#include <algorithm>#include <functional>#include <string>#include <utility>#include <map>#include <cmath>#include <iomanip>using namespace std;const int maxn=110;const int inf=0x3f3f3f3f;typedef pair<int,int> P;struct p{    int l,r;}sta[maxn];bool cmp(p a, p b){    if(a.r!=b.r) return a.r<b.r;    return a.l<b.l;}int main(){        int n;        while(scanf("%d",&n)==1&&n)        {            memset(sta,0,sizeof(sta));            for(int i=0;i<n;i++) scanf("%d%d",&sta[i].l,&sta[i].r);            sort(sta,sta+n,cmp);            int cnt=1;            int b=sta[0].r;            for(int i=0;i<n;i++)            {                if(sta[i+1].l>=b)                {                    cnt++;                    b=sta[i+1].r;                }            }            printf("%d\n",cnt);        }}