bzoj1637 [Usaco2007 Mar]Balanced Lineup

时间:2023-03-09 16:13:09
bzoj1637 [Usaco2007 Mar]Balanced Lineup

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

输入说明



有7头牛,像这样在数轴上。



1 1 0 1 0 1 1

+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

输出说明



牛 #1 (at 11), #4 (at 12), #6 (at 13), #7 (at 22) 组成一个平衡的最大的区间,大小为 22-11=11 个单位长度。




<-------- 平衡的 -------->

1 1 0 1 0 1 1

+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

离散+差分序列搞

把01的标识改成1和-1,然后离散完用差分序列维护。这样搞只要找到最前面第一个前缀和和它相等的更新答案就好了

注意到差分的范围是-50000到50000,所以还要化负为正

#include<cstdio>
#include<algorithm>
using namespace std;
#define add 50010
struct dat{
int x,v;
}d[50010];
inline bool operator < (dat a,dat b){return a.x<b.x;}
inline int max(int a,int b)
{return a>b?a:b;}
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,now=add,ans;
int last[100050];
int main()
{
n=read();
for (int i=1;i<=n;i++)
{
d[i].v=read();d[i].x=read();
if (!d[i].v)d[i].v=-1;
}
sort(d+1,d+n+1);
for (int i=1;i<=n;i++)
{
now+=d[i].v;
if (!last[now])last[now]=d[i+1].x;
else ans=max(ans,d[i].x-last[now]);
}
printf("%d",ans);
}