http://acm.hdu.edu.cn/showproblem.php?pid=5400
Arithmetic Sequence
Time Limit: 4000/2000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1151 Accepted Submission(s): 501
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.
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).
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
12
5
题目大意:有一种区间[l,r],存在i使得当l<=j<=i时,a[j+1]=a[j]+d1,当i<=j<=r时a[j+1]=a[j]+d2;
其实这种区间就是[l,i]区间a中元素是以d1位公差的等差数列,[i,r]区间a中的元素是以d2为公差的等差数列
求这样的区间有多少种
枚举i(1<=i<=n),预处理出以i为中心,左侧是满足以d1为公差的等差数列的最大长度al[ i ],
右侧是满足以d2为公差的等差数列的最大长度ar[ i ];
1、如果d1=d2, 那么以i为一个解的区间个数为 ans +=al[i](或ar[i]);
2、如果d1!=d2, 那么以i为一个解的区间个数为al[ i ]*ar[ i ]
#include<stdio.h> #include<string.h> #include<math.h> #include<stdlib.h> #include<algorithm> #define N 100010 using namespace std; long long a[N], al[N], ar[N];//al[i]表示从左边开始(以d1为公差的等差数列)记录元素的个数,ar[i]表示从右边开始(以d2为公差的等差数列)记录元素的个数 int main() { long long n, d1, d2, i; while(~scanf("%lld%lld%lld", &n, &d1, &d2)) { for(i = 1 ; i <= n ; i++) scanf("%lld", &a[i]); al[1] = ar[n] = 1;//初始化,最开始从左边开始i=1和从右边开始i=n时等差数列中的元素个数都为1 for(i = 2 ; i <= n ; i++) { if(a[i] == a[i - 1] + d1) al[i] = al[i - 1] + 1;//如果满足条件即a[i]是以d1为公差的等差数列里的元素,所以元素个数在本来的基础上+1 else al[i] = 1;//不满足条件则a[i]不是以d1为公差的等差数列里的元素,此时a[i]是另一个数列。其元素个数为1 } for(i = n - 1; i >= 1 ; i--) { if(a[i] == a[i + 1] - d2)//由a[i+1]=a[i]+d2转化而来 ar[i] = ar[i + 1] + 1; else ar[i] = 1; } long long ans = 0; for(i = 1 ; i <= n ; i++) { if(d1 == d2) ans += al[i]; else ans += al[i] * ar[i]; } printf("%lld ", ans); } return 0; }