Problem H: H-Sum 3s
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 77 Solved: 10
[ Submit][ Status][ Web Board]
Description
You are given a number sequence a
1,a
2,a
3...,a
n , your task is to find if there is a pair of interger (i,j) that a
i+a
(i+1)+..+a
j equals to 0 and i<=j;
Input
Input consists of multiple test cases. For each case, the first line of input contains an integer n, the next line follows n integers. (n>=1 && n<=10^5 |ai|<=10^4)
Output
For each case, if there is at least one pair of integer (i,j) meet the requirement, print “YES”, otherwise print “NO” .
Sample Input
51 2 3 4 553 4 -2 -3 1
Sample Output
NOYES
HINT
AC代码:
#include <iostream>
using namespace std;
int main(){
int n;
while(cin>>n){
int a[n];
int sum=0,i=0,k=0,s1,t1,t2,j;;
while(i<n){
cin>>a[i];
sum+=a[i];
if(a[i]==0||sum==0)k++;
if(k==0){
for(j=0,t2=0;j<i-1;j++){
t1=a[j];
t2+=t1;
s1=sum-t2;
if(s1==0){
k++;
break;
}
}
}
i++;
}
if(k==0) cout<<"NO"<<'\12';
else cout<<"YES"<<'\12';
}
return 0;
}
运行结果:
心得:
这看起来是一道很简单的题,2个循环就出来了。但如果这样oj平台会给出时间超限的提示。所以要想办法减少计算时间,我是在输入数据的同时完成部分运算。谢天谢地在错误9次后终于ac了。感觉棒!