51Nod 1091 (贪心)

题意:
给出n个区间,求两个区间重叠长度的最大值。


思路:
贪心。根据左端点由小到大排序,相同时右端点大的在前面。从最左边的区间开始,维护当前已处理区间中到达的最右边的点mx,这时有三种情况:
1、mx小于左端点,前面的区间中与当前区间没有重叠。
2、mx大于左端点,小于右端点,部分重叠,计算重叠长度更新答案。
3、mx大于左端点,大于右端点,前面的区间覆盖了当前区间,用当前区间长度更新答案。


代码:

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <map>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <sstream>
#define pb push_back
#define X first
#define Y second
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define pii pair<int,int>
#define qclear(a) while(!a.empty())a.pop();
#define lowbit(x) (x&-x)
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define mst(a,b) memset(a,b,sizeof(a))
#define cout3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl
#define cout2(x,y) cout<<x<<" "<<y<<endl
#define cout1(x) cout<<x<<endl
#define IOS std::ios::sync_with_stdio(false)
#define SRAND srand((unsigned int)(time(0)))
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
using namespace std;
const double PI=acos(-1.0);
const int INF=0x3f3f3f3f;
const ll INFF=0x3f3f3f3f3f3f3f3f;
const ll mod=998244353;
const double eps=1e-5;
const int maxn=50005;
const int maxm=20005;
struct node{
    int l,r;
    bool operator < (const node b)const{
        if(l==b.l) return r>b.r;
        return l<b.l;
    }
};
int n;
node a[maxn];
void solve() {
    sd(n);
    for(int i=0;i<n;i++){
        sdd(a[i].l,a[i].r);
    }
    sort(a,a+n);
    int ans=0;
    int mx=a[0].r;
    for(int i=1;i<n;i++){
        if(mx>a[i].l){
            if(mx<=a[i].r)ans=max(ans,mx-a[i].l);
            else ans=max(ans,a[i].r-a[i].l);
            mx=max(mx,a[i].r);
        }
    }
    printf("%d\n",ans);
    return ;
}
int main() {
#ifdef LOCAL
    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
#else
    //    freopen("","r",stdin);
    //    freopen("","w",stdout);
#endif
    solve();
    return 0;
}


 

猜你喜欢

转载自blog.csdn.net/weixin_38378637/article/details/81146041
今日推荐