BOJ 262 Channel Coding

本文介绍了一种简单而有效的哈希方法来解决特定整数序列问题。目标是在一个仅包含0、1和-1的整数序列中找到能使任意子序列和为0的最大间隔D。文章提供了完整的C语言实现代码,并通过示例输入输出展示了算法的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Description
Assume an integer sequence contains N elements whose value could only be one of {0, 1, -1}. There may exist a positive integer D which can make the sum between i-th element and (i+D)-th element be zero, where i is a certain integer between 1 and N-D. Your task is to find out the maximal D.

Input
First line contains a integer T indicate the number of cases. (T<=50)
In each test case, the first line is N descript above. (N<=50000)
Then follows N integers the sequence contains.


Output
Each case output one integer D in a line. If there is no such a D, just output -1.

Sample Input

2
3
1 0 -1
1
1


Sample Output

2
-1

很简单的hash

#include<stdio.h>
#include<stdlib.h>;
#include<string.h>
#define inf 100001
int Max(int a,int b){
	return a>b?a:b;
}
int Min(int a,int b){
	return a>b?b:a;
}
int max[100100],min[100100],res;
int main(){
	int i,j,n,T,t,tem;
	scanf("%d",&T);
	for(t=1;t<=T;t++){
		scanf("%d",&n);
		int sum=0;
		res=-1;
		for(i=0;i<=2*n;i++){
			max[i]=0;
			min[i]=inf;
		}
		max[0]=0,min[0]=0;
		for(i=1;i<=n;i++){
			scanf("%d",&tem);
			sum+=tem;
			if(sum<0){
				min[n-sum]=Min(min[n-sum],i);
				max[n-sum]=Max(max[n-sum],i);
				res=Max(res,max[n-sum]-min[n-sum]);
			}
			else{
				min[sum]=Min(min[sum],i);
				max[sum]=Max(max[sum],i);
				res=Max(res,max[sum]-min[sum]);
			}
		}
		if(res>1)
			printf("%d\n",res-1);
		else
			printf("-1\n");
	}
	return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值