hdu 5400 Arithmetic Sequence

题目链接:

http://acm.hdu.edu.cn/showproblem.php?pid=5400

解题思路:

首先预处理出来出ii这个位置向前d_1d1的等差序列和向后d_2d2的等差数列能延续到多长,记作l_i,r_ili,ri

如果d_1\neq d_2d1d2,那么枚举中间位置,答案为l_i*r_iliri

如果d_1=d_2d1=d2,枚举开始位置,答案为r_iri

只能说自己基础还不扎实,明明想的已经和标答一样了,然而写代码时没有这么记忆化标记,每个位置的l,r都是重新求得,导致超时。。。还要多多学习呀。。。

AC代码:

#include <iostream>
#include <cstdio>
using namespace std;

typedef long long ll;
int a[100005];
ll l[100005],r[100005];

int main(){
    int n,d1,d2;
    while(~scanf("%d%d%d",&n,&d1,&d2)){
        for(int i = 1; i <= n; i++)
            scanf("%d",&a[i]);
        ll ans = 0;
        if(d1 == d2){
            ll sum = 1;
            for(int i = 2; i <= n; i++){
                if(a[i] == a[i-1]+d1)
                    sum++;
                else{
                    ans += (sum+1)*sum/2;
                    sum = 1;
                }
            }
            ans += (sum+1)*sum/2;
        }
        else{
            l[0] = 0;r[n+1] = 0;
            for(int  i = 1; i <= n; i++){
                if(a[i] == a[i-1]+d1)
                    l[i] = l[i-1]+1;
                else
                    l[i] = 1;
            }
            for(int i = n; i >= 1; i--){
                if(a[i] == a[i+1]-d2)
                    r[i] = r[i+1]+1;
                else
                    r[i] = 1;
            }
            for(int i = 1; i <= n; i++)
                ans += (l[i]*r[i]);
        }
        printf("%lld\n",ans);
    }
    return 0;
}


你可能感兴趣的:(找规律)