关闭

USACO 1.2 Milking Cows

73人阅读 评论(0) 收藏 举报
分类:

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.

PROGRAM NAME: milk2

INPUT FORMAT

Line 1: The single integer, N
Lines 2..N+1: Two non-negative integers less than 1,000,000, respectively the starting and ending time in seconds after 0500

SAMPLE INPUT (file milk2.in)

3
300 1000
700 1200
1500 2100

OUTPUT FORMAT

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

SAMPLE OUTPUT (file milk2.out)

900 300

比较简单的一道数据结构题,但对我来说还是有点难度的。。

关键在于区间标记。我一开始的做法是对于给出的区间【a,b】,标记a和b+1.理想很美好,现实很残酷,这种标记是错误的。为啥大家可以自己想一下。

(100 200

    201 300

那就只能a,b标记,这样又有一个问题,就是连续不放羊的天数会有错误。经过多次数据测试,我们知道了:如果从头到尾都是放羊,那么结果要-1.

/*
ID: myk5021
PROG: milk2
LANG: C++11
*/
#include<cstdio>
#include<iostream>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<climits>
using namespace std;
const int maxn=1000000+10;
int n,a[maxn],sum_a[maxn];
int main(void)
{
    freopen("milk2.in","r",stdin);
    freopen("milk2.out","w",stdout);
    int ans1=0,ans2=0,left,right,continue_0,continue_1,lmin=maxn,rmax=0;
    memset(a,0,sizeof(a));
    memset(sum_a,0,sizeof(sum_a));
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>left>>right;
        a[left]+=1;
        a[right]-=1;
        rmax=max(rmax,right);
        lmin=min(lmin,left);
    }
    sum_a[0]=a[0];
    for(int i=1;i<=rmax;i++)
        sum_a[i]=sum_a[i-1]+a[i];
    continue_1=continue_0=0;
    for(int i=lmin;i<=rmax;i++)
    {
        if(sum_a[i]==0)
        {
            continue_0++;
            continue_1=0;
        }
        else
        {
            continue_1++;
            continue_0=0;
        }
        ans1=max(ans1,continue_1);
        ans2=max(ans2,continue_0);
    }
    if(rmax-lmin==ans1)
    {
        ans2--;
    }
    printf("%d %d\n",ans1,ans2);
    return 0;
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:18117次
    • 积分:1223
    • 等级:
    • 排名:千里之外
    • 原创:105篇
    • 转载:16篇
    • 译文:0篇
    • 评论:9条
    最新评论