[BZOJ1637][Usaco2007 Mar]Balanced Lineup

1637: [Usaco2007 Mar]Balanced Lineup

Time Limit: 5 Sec  Memory Limit: 64 MB Submit: 693  Solved: 460 [Submit][Status][Discuss]

Description

Farmer John 决定给他的奶牛们照一张合影,他让 N (1 ≤ N ≤ 50,000) 头奶牛站成一条直线,每头牛都有它的
坐标(范围: 0..1,000,000,000)和种族(0或1)。 一直以来 Farmer John 总是喜欢做一些非凡的事,当然这次照相
也不例外。他只给一部分牛照相,并且这一组牛的阵容必须是“平衡的”。平衡的阵容,指的是在一组牛中,种族
0和种族1的牛的数量相等。 请算出最广阔的区间,使这个区间内的牛阵容平衡。区间的大小为区间内最右边的牛
的坐标减去最做边的牛的坐标。 输入中,每个种族至少有一头牛,没有两头牛的坐标相同。

Input

行 1: 一个整数: N 行 2..N + 1: 每行两个整数,为种族 ID 和 x 坐标。

Output

行 1: 一个整数,阵容平衡的最大的区间的大小。

Sample Input

7
0 11
1 10
1 25
1 12
1 4
0 13
1 22

Sample Output

11
 
把两个种族的牛分别标为$+1$或$-1$,$(i,j]$合法的充要条件为$sum[j]-sum[i]=0$,那么记录一下每种值的最早出现位置就行了
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char buf[10000000], *ptr = buf - 1;
inline int readint(){
    int f = 1, n = 0;
    char ch = *++ptr;
    while(ch < '0' || ch > '9'){
        if(ch == '-') f = -1;
        ch = *++ptr;
    }
    while(ch <= '9' && ch >= '0'){
        n = (n << 1) + (n << 3) + ch - '0';
        ch = *++ptr; 
    }
    return f * n;
}
const int maxn = 50000 + 10;
struct Node{
    int id, x;
    Node(){}
    Node(int _id, int _x): id(_id), x(_x){}
    bool operator < (const Node &a) const {
        return x < a.x;
    }
}a[maxn];
int N, l[maxn * 2] = {0};
int main(){
    fread(buf, sizeof(char), sizeof(buf), stdin);
    N = readint();
    for(int i = 1; i <= N; i++){
        a[i].id = readint();
        a[i].x = readint();
    }
    sort(a + 1, a + N + 1); 
    int ans = 0;
    for(int sum = 0, i = 1; i <= N; i++){
        if(a[i].id == 1) sum++;
        else sum--;
        if(sum == 0) ans = max(ans, a[i].x - a[1].x);
        else{
            if(l[sum + N] != 0) ans = max(ans, a[i].x - a[l[sum + N] + 1].x);
            else l[sum + N] = i;
        }
    }
    printf("%d\n", ans);
    return 0;
}

 

posted @ 2017-09-16 16:14  jzyy  阅读(197)  评论(0编辑  收藏  举报