[BZOJ1637][Usaco2007 Mar]Balanced Lineup

传送门

http://www.lydsy.com/JudgeOnline/problem.php?id=1637

题目大意

给n个位置上有两种物品,选出两种物品数相同的最大区间长度

题解

非常神奇的前缀和ORZ
我们可以发现两个种类如果分别定义为1和-1,那么要选取的[L,R]的区间和一定为0,那么sum[L-1]=sum[R],然后扫一遍就可以了

var
 sum,x,y:array[0..50000]of longint;
 t:array[-50000..50000]of longint;
 i,j,k:longint;
 ans,n:longint;
function max(a,b:longint):longint;
begin
 if a>b then exit(a) else exit(b);
end;

procedure sort(l,r:longint);
var i,j,a,b: longint;
begin
 i:=l; j:=r; a:=x[(l+r) div 2];
 repeat
  while x[i]<a do inc(i);
  while a<x[j] do dec(j);
  if not(i>j) then
   begin
    b:=x[i]; x[i]:=x[j]; x[j]:=b;
    b:=y[i]; y[i]:=y[j]; y[j]:=b;
    inc(i); dec(j);
   end;
 until i>j;
 if l<j then sort(l,j);
 if i<r then sort(i,r);
end;

begin
 readln(n);
 for i:=1 to n do
  begin readln(y[i],x[i]); if y[i]=0 then y[i]:=-1; end;
 sort(1,n); {x[i]}
 ans:=0; sum[0]:=0; fillchar(t,sizeof(t),0);
 for i:=1 to n do
  begin
   sum[i]:=sum[i-1]+y[i];
   if t[sum[i]]=0
   then t[sum[i]]:=x[i+1]
   else ans:=max(ans,x[i]-t[sum[i]]);
  end;
 writeln(ans);
end.

你可能感兴趣的:([BZOJ1637][Usaco2007 Mar]Balanced Lineup)