hash——http://www.zybbs.org/JudgeOnline/problem.php?id=1637

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
View Code
#include<iostream>
#include<stdio.h>
#include<algorithm>
using namespace std;

struct data
{
int z;
int no;
}node[50009];
int sum[50009];

int cmp(data a,data b)
{
return a.no<b.no;
}

int hash[1000009];

int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
int i;
for(i=1;i<=n;i++)
{
sum[i]=0;
scanf("%d%d",&node[i].z,&node[i].no);

if(node[i].z==0)node[i].z=-1;
}

sort(&node[1],&node[1+n],cmp);
sum[1]=node[1].z;
for(i=2;i<=n;i++)
{
sum[i]+=sum[i-1];
}

for(i=1;i<=n;i++)
{
if(hash[sum[i]+50000]==0)
{
hash[sum[i]+50000]=i;
}
}

int max=0,temp;
for(i=n;i>=1;i--)
{
if(hash[sum[i]+50000]!=0)
{
if(hash[sum[i]+50000]>=i) continue;

temp=node[i].no-node[hash[sum[i]+50000]+1].no;
if(max<temp)
max=temp;
}
}

printf("%d\n",max);
}
}
原文地址:https://www.cnblogs.com/huhuuu/p/2206646.html