- 求和游戏
Description
石柱上有一排石头键盘,每个键上有一个整数。请你在键盘上选择两个键,使这两个键及其之间的键上的数字和最大。如果这个最大的和不为正,则输出“Game Over”。
Input Format
第1行:键的个数n。
第2..n+1行:键上的数字整数 ai
。
−100≤ai≤100
对于70%的数据,2≤n≤1,000
对于100%的数据,2≤n≤1,000,000
Output Format
一行,最大和或者”Game Over”。
Sample Input
5
3
-5
7
-2
8
Sample Output
13
Sample Input
3
-6
-9
-10
Sample Output
Game Over
此题我用了两种办法来解决它,不过两种方法其实是一样的,首先给出最初的版本
#include<iostream>
using namespace std;
int n;
int a[1000002];
int main(){
cin>>n;
for(int i=1;i<=n;i++){
cin>>a[i];
}
int max=-200,t1 = 0,t2 = 0;
max = a[1]+a[2];
int max1=-200,t11=0,t22=0;
max1 = a[n]+a[n-1];
for(int i=n;i>=3;i--){
t11 += a[i];
if(t11 < 0){
t11 = 0;
t22 = 0;
continue;
}
t22++;
if(t11 > max1 && t22 > 1){
max1 = t11;
}
}
for(int i=3;i<=n;i++){
t1 += a[i];
if(t1 < 0){
t1 = 0;
t2 = 0;
continue;
}
t2++;
if(t1 > max && t2 > 1){
max = t1;
}
}
max = max > max1 ? max:max1;
if(max > 0)
cout<<max;
else
cout<<"Game Over";
return 0;
}
最后的版本:
#include<iostream>
#include<cstdio>
#include<malloc.h>
using namespace std;
int info[1000001];
int main()
{
int n, max, tmp;
scanf("%d",&n);
info[0] = 0;
for(int i = 1; i <= n; i++)
scanf("%d",&info[i]);
max = tmp = info[1]+info[2];
for(int i = 3; i <= n; i++){
tmp = tmp > info[i-1]? tmp+info[i]:info[i]+info[i-1];
max = tmp > max? tmp:max;
}
(max <= 0)? printf("Game Over"):printf("%d",max);
return 0;
}
整体思想,不好说,有兴趣的朋友,带一个样例进去就懂了