题目描述
You are given a number sequence a1,a2,a3...,an , your task is to find if there is a pair of interger (i,j) that ai+a(i+1)+..+aj equals to 0 and i<=j;
输入
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)
输出
For each case, if there is at least one pair of integer (i,j) meet the requirement, print “YES”, otherwise print “NO” .
样例输入
5
1 2 3 4 5
5
3 4 -2 -3 1
样例输出
NO
YES
提示
代码如下:
#include <iostream> #include <algorithm> using namespace std; int main() { int N; while (cin>>N) { int i,k=0,a[100000],s[100000]; cin>>a[0]; s[0]=a[0]; if (a[0]==0) k=1; for (i=1; i<N; i++) { cin>>a[i]; s[i]=s[i-1]+a[i]; if (a[i]==0||s[i]==0) k=1; } if (k==0) { sort(s,s+N); for (i=0; i<N-1; i++) { if (s[i]==s[i+1]) { k=1; break; } } } if (k==1) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
学习心得:
图就不发了,今天上午去机房,机房维护不开门,4408也是,,,我只能默默地回到宿舍敲代码,借的隔壁同学的塞尔网登陆OJ提交的。。。错了一次之后AC了
这道题时间超限了两次,用的枚举,算法花费的时间等于N*N,实在低下,,,请教大神之后有了思路,于是写了新的代码,但是没有注意数组越界的问题,第一次直接WA。
找到问题后修改过了第二次就AC了。。。
sort是头文件algorithm自带的排序函数,以后妈妈再也不用担心我的排序了。。。当然基础的还是得掌握的,还有hash和归并排序没有搞懂,