Arithmetic Sequence
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1802 Accepted Submission(s): 783
Problem Description
A sequence
b1,b2,⋯,bn
are called
(d1,d2)
-arithmetic sequence if and only if there exist
i(1≤i≤n)
such that for every
j(1≤j<i),bj+1=bj+d1
and for every
j(i≤j<n),bj+1=bj+d2
.
Teacher Mai has a sequence
a1,a2,⋯,an
. He wants to know how many intervals
[l,r](1≤l≤r≤n)
there are that
al,al+1,⋯,ar
are
(d1,d2)
-arithmetic sequence.
Input
There are multiple test cases.
For each test case, the first line contains three numbers
n,d1,d2(1≤n≤105,|d1|,|d2|≤1000)
, the next line contains
n
integers
a1,a2,⋯,an(|ai|≤109)
.
Output
For each test case, print the answer.
Sample Input
5 2 -2
0 2 0 -2 0
5 2 3
2 3 3 3 3
Sample Output
Author
xudyh
Source
给你长度为n的序列,求有多少个连续的子序列满足前一半公差d1,后一半公差d2.
先求出连续的公差d1、d2的序列长度。然后讨论:
1.子序列长度为1,共n个符合要求的序列。
2.子序列公差为d1或d2,设长度为len,共有len*(len+1)/2个子序列符合要求。
3.公差d1、d2的序列连在一起,我们在前一段选一个头,后一段选一个尾。设长度分别为lena、lenb,
共有lena*lenb种答案。
#include <cstdio>
#include <iostream>
#include <string.h>
#include <string>
#include <map>
#include <queue>
#include <vector>
#include <set>
#include <algorithm>
#include <math.h>
#include <cmath>
#include <stack>
#define mem0(a) memset(a,0,sizeof(a))
#define meminf(a) memset(a,0x3f,sizeof(a))
using namespace std;
typedef long long ll;
typedef long double ld;
const int maxn=1000005,inf=0x3f3f3f3f;
const ll llinf=0x3f3f3f3f3f3f3f3f;
const ld pi=acos(-1.0L);
ll a[maxn],lena[maxn],lenb[maxn];
int main() {
int n,i;
ll d1,d2;
while (scanf("%d%lld%lld%lld",&n,&d1,&d2,&a[1])!=EOF) {
mem0(lena);mem0(lenb);
for (i=2;i<=n;i++) {
scanf("%lld",&a[i]);
if (a[i]-a[i-1]==d1) lena[i]=lena[i-1]+1; else
if (a[i]-a[i-1]==d2) lenb[i]=lenb[i-1]+1;
}
ll ans=n,last=-1;
lena[n+1]=lenb[n+1]=0;
for (i=2;i<=n+1;i++) {
if (lena[i-1]!=0&&lena[i]==0) {
ans+=lena[i-1]*(lena[i-1]+1)/2;
last=i-1;
} else if (lenb[i-1]!=0&&lenb[i]==0) {
if (last==i-1-lenb[i-1]) ans+=lena[last]*lenb[i-1];
ans+=lenb[i-1]*(lenb[i-1]+1)/2;
}
}
printf("%lld\n",ans);
}
return 0;
}