4.22 One problem per day

Xiao Sun's Holiday

Knowledge points involved:

  • Enumeration / double pointer / interval merge

solution:

  • \ (The title is to let you output the largest uncovered interval length \)
  • \ (First sort according to l from small to large, if l is equal, sort according to r from small to large \)
  • \ (When will there be a connected holiday? Initialize j = 1, i = 2, similar to double pointer \)
  • \ (Traversing i, a [j] .r <= a [i] .l (i> j), the vacation length is a [i] .l-a [j] .r-1, then let j = i \)
  • $ Otherwise, if a [j] .r> a [i] .l, the two intervals intersect, and there is no vacation, a [j] .r should be updated to max (a [j] .r, a [i]. r]) $
  • \ (About the left end point and the right end point, need to discuss by situation, in order to be less troublesome, I added two intervals: \)
  • \(a[++n].l = 0,a[n].r = 0;a[++n].l = m+1,a[n].r = m+1;\)

std:

#include <bits/stdc++.h>
using namespace std;
#define ll long long
const int maxx = 100005;
struct node{
    int l,r;
}a[maxx];
bool cmp(node p1,node p2){
    if(p1.l == p2.l)
        return p1.r < p2.r;
    return p1.l < p2.l;
}
int main()
{
    int n,m,ans = 0;
    scanf("%d %d",&m,&n);
    for(int i=1;i<=n;i++){
        scanf("%d %d",&a[i].l,&a[i].r);
    }
    a[++n].l = 0,a[n].r = 0;
    a[++n].l = m+1,a[n].r = m+1;
    sort(a+1,a+1+n,cmp);
    for(int i=2,j=1;i<=n;i++)
    {
        if(a[i].l <= a[j].r)
            a[j].r = max(a[j].r,a[i].r);
        else{
            ans = max(ans,a[i].l - a[j].r -1);
            j = i;
        }
    }
    cout<<ans<<endl;
    return 0;
}

Guess you like

Origin www.cnblogs.com/QFNU-ACM/p/12749650.html