Algorithm Design and Analysis section 1.4

★ Title Description

There are N intervals, the endpoint is the i-th interval li and ri, i.e. the i-th interval coverage [li, RI]

Is there a minimum number of interval contains all of the range. If present, the output interval number, otherwise output "-1."

It refers to a section comprising, assuming an interval [a, b] comprising a further interval [c, d], needs to satisfy a <= c <= d <= b.

★ input format

The first line represents an integer number of intervals N, N <= 100000

Next N lines two integers li, ri denotes the i th interval endpoints, 1 <= li <= ri <= 1000000000

For 30% of the data, N <= 100, 1 <= li <= ri <= 100

For 80% of data, N <= 1000, 1 <= li <= ri <= 1000

To 100% of the data, N <= 100000, 1 <= li <= ri <= 1000000000

★ output format

Integer meet the requirements of a range of numbers. If there is output -1.

★ sample input

3
1 1
2 2
3 3

★ Sample Output

-1
/*
直切要点:
如果存在一个区间包含所有其他区间
那么该区间的长度一定最大 
*/

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n;
    cin>>n;
    
    int l,r,minL,maxR;
    scanf("%d%d",&minL,&maxR);
    int resL=minL,resR=maxR, resid=1; //如果是答案区间,那么该区间长度一定最大 
    for(int i=2; i<=n; ++i){
        scanf("%d%d",&l,&r);
        minL = min(l,minL);
        maxR = max(r,maxR);
        
        if(resR-resL<r-l) resL=l,resR=r,resid=i; 
    }
    
    if(resL==minL && resR==maxR) printf("%d\n",resid);
    else printf("-1\n"); 
    return 0;
}

Guess you like

Origin www.cnblogs.com/yejifeng/p/12044333.html