金山游戏编程复赛 连续最大积
连续最大积
Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others) Total Submission(s): 1383 Accepted Submission(s): 261
Problem Description
小明和他的好朋友小西在玩一个游戏,由电脑随机生成一个由-2,0,2三个数组成的数组,并且约定,谁先算出这个数组中某一段连续元素的积的最大值,就算谁赢!
比如我们有如下随机数组: 2 2 0 -2 0 2 2 -2 -2 0 在这个数组的众多连续子序列中,2 2 -2 -2这个连续子序列的积为最大。
现在小明请你帮忙算出这个最大值。
比如我们有如下随机数组: 2 2 0 -2 0 2 2 -2 -2 0 在这个数组的众多连续子序列中,2 2 -2 -2这个连续子序列的积为最大。
现在小明请你帮忙算出这个最大值。
Input
第一行输入一个正整数T,表示总共有T组数据(T <= 200)。 接下来的T组数据,每组数据第一行输入N,表示数组的元素总个数(1<= N <= 10000)。 再接下来输入N个由0,-2,2组成的元素,元素之间用空格分开。
Output
对于每组数据,先输出Case数。 如果最终的答案小于等于0,直接输出0 否则若答案是2^x ,输出x即可。 每组数据占一行,具体输出格式参见样例。
Sample Input
2
2
-2 0
10
2 2 0 -2 0 2 2 -2 -2 0
Sample Output
Case #1: 0
Case #2: 4
// 刚开始没思路 , 后来想到枚举
// 很神奇的过了, 其他三题不会= =
// 1001 234MS 244K G++
#include<cstdio>
#include<cmath>
#include<cstring>
using namespace std ;
int ans[10001] ;
struct node
{
int s , e , ok ;
}qe[10001] ;
int main()
{
int i , n , m , Max , sum , j ;
int T ,ok , Case = 0 , len , k ;
scanf( "%d" , &T ) ;
while( T-- )
{
scanf( "%d" , &n ) ;
for( i = 1 ; i <= n ;i++){
scanf( "%d" , &m ) ;
if( m == -2 ) ans[i] = -1 ;
else if( m == 2 ) ans[i] = 1 ;
else ans[i] = 0 ;
}
Max = 0 ;int mun = 0 ; len = 0 ;
// 把连续的不是0 的读出来
// 还有记录是不是奇数
for( i = 1 ; i <= n ;i++)
{
if( ans[i] != 0 )
{
qe[len].s = i ;ok = 0 ;mun = 0 ;
qe[len].ok = 0 ;
for( j = i ; j <= n ;j++ )
{
if( ans[j] == 0){ ok = 1 ; break ;}
if( ans[j] == -1 ) mun++ ;
}
if( mun%2) qe[len].ok = 1 ;
if(ok)
qe[len++].e = j - 1 ;
else qe[len++].e = n ;
i = j ;
}
}
// 在每个连续的而且个数1是奇数里面枚举 两边
// 如果是偶数则肯定都要
for( i = 0 ; i < len ;i++ ){
if( qe[i].ok )
{
for( j = qe[i].s ; j <= qe[i].e ;j++ )
if( ans[j] == -1 )
{
if( j - qe[i].s > Max ) Max = j - qe[i].s ;
if( qe[i].e - j > Max ) Max = qe[i].e - j ;
}
}
else if( qe[i].e - qe[i].s + 1 > Max ) Max = qe[i].e - qe[i].s + 1 ;
}
printf( "Case #%d: %d\n" , ++Case , Max ) ;
}
}

浙公网安备 33010602011771号