描述
Given a sequence including N integers, we define the ith element "good" if it equals the sum of three elements strictly before the position i (an element can be used more than once).
Please tell me the number of good elements int this sequence?
输入
The first line is an integer N (1 <= N <= 5000), and the next line has N integers indicating the elements of the sequence, each element is between -100000 and 100000.
输出
Output an integer indicating the number of good elements in the sequence.
样例输入
2
1 3
5
1 2 3 4 5
样例输出
1
3
计算出前面每两项之和, 用要判断的那一个数 减去前面的, 如果它们的结果存在的话 (这里用1标记), 就说明是好数。
#include <iostream> using namespace std; int num[400005]={0}; //存两数之和是否存在,有负数 ,所以要开大点 int a[5005]; int main() { int n,m,i,j,flag,ans=0; cin>>n; for(i=1;i<=n;i++) scanf("%d",&a[i]); for(i=1;i<=n;i++){ for(j=1;j<i;j++){ num[a[i-1]+a[j]+200000]=1; } for(j=1;j<i;j++){ if(num[a[i]-a[j]+200000]==1){ ans++; break; } } } cout<<ans<<endl; }