欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

TOJ 3311 排序+区间端点

程序员文章站 2024-03-18 22:08:10
...

3311: Milking Cows 分享至QQ空间
时间限制(普通/Java):1000MS/3000MS 内存限制:65536KByte
总提交: 148 测试通过:35
描述

Three farmers rise at 5 am each morning and head for the barn to milk three cows. The first farmer begins milking his cow at time 300 (measured in seconds after 5 am) and ends at time 1000. The second farmer begins at time 700 and ends at time 1200. The third farmer begins at time 1500 and ends at time 2100. The longest continuous time during which at least one farmer was milking a cow was 900 seconds (from 300 to 1200). The longest time no milking was done, between the beginning and the ending of all milking, was 300 seconds (1500 minus 1200).

Your job is to write a program that will examine a list of beginning and ending times for N (1 <= N <= 5000) farmers milking N cows and compute (in seconds):

The longest time interval at least one cow was milked.

The longest time interval (after milking starts) during which no cows were being milked.

输入

Line 1: The single integer

Lines 2…N+1: Two non-negative integers less than 1000000, the starting and ending time in seconds after 0500

输出

A single line with two integers that represent the longest continuous time of milking and the longest idle time.

样例输入

3
300 1000
700 1200
1500 2100

样例输出

900 300

题目来源

USACO

题意:给你几个区间,问最大的连续区间和最大的不连续区间。

#include<bits/stdc++.h>
using namespace std;
struct node{
    int x,y;
}q[5005];
bool cmp(node a,node b){
    return a.x<b.x; // 按左端点排序
}
int main(){
    int n;
    __int64 ans=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
        scanf("%d%d",&q[i].x,&q[i].y);
    sort(q,q+n,cmp);
    ans=q[0].y-q[0].x; //ans记录当前的连续区间长度
    int minx=q[0].x,miny=q[0].y; //记录当前的连续长度的断电
    __int64 maxn=miny-minx,mmin=0; //初始化最大连续和最小连续
    for(int i=1;i<n;i++){
        if(q[i].x<=miny){ //如果连续
            miny=max(miny,q[i].y);  //取两个区间大的右端点。
            ans=miny-minx; //更新ans
        }
        else{
            if(ans>maxn) maxn=ans; //不相交,更新最大的连续区间
            int t=q[i].x-miny; //不相交的区间
            if(t>mmin) mmin=t; // 更新 最大的不连续区间
            minx=q[i].x,miny=q[i].y; //重新寻找下一个连续区间
        }
    }
    printf("%I64d %I64d\n",maxn,mmin);

}

相关标签: 杂题