HDOJ 5328 Problem Killer 【等差等比數列】

HDOJ 5328 Problem Killer 【等差等比數列】

題目鏈接 http://acm.hdu.edu.cn/showproblem.php?pid=5328


…wa了n次…
1、 if(i == 1) AP = 1; else AP =2; // ap、gp出現重複的時候 eg: 7 1 2 3 1 2 3 4
2、 APmax = APmax>AP ? APmax : AP; // 沒有進入 else 的時候 eg: 3 1 2 3
3、(double)a[i] / (double)a[i-1] // 轉double

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
typedef long long ll;
const int MAXN = 1e6+5;
int a[MAXN];
int T, n;
int AP, GP;
int APmax, GPmax;
int APd;
double GPq;

void Resolve(){
    AP = 1;
    GP = 1;
    APmax = 1;
    GPmax = 1;
    for(int i = 2; i <= n; i++){
        if(a[i] - a[i-1] == APd) AP++;
        else{
            APd = a[i] - a[i-1];
            APmax = APmax>AP ? APmax : AP;
            if(i == 1) AP = 1;
            else AP =2;
        }
    }
    APmax = APmax>AP ? APmax : AP;

    for(int i = 2; i <= n; i++){
        if((double)a[i] / (double)a[i-1] == GPq) GP++;
        else{
            GPq = (double)a[i] / (double)a[i-1];
            GPmax = GPmax>GP ? GPmax : GP;
            if(i == 1)GP = 1;
            else GP = 2;
        }
    }
    GPmax = GPmax>GP ? GPmax : GP;

    //printf("%d\t%d\n", APmax, GPmax);
    if(n == 1) printf("1\n");
    else printf("%d\n", APmax>GPmax ? APmax: GPmax);
}

int main(){
    scanf("%d", &T);
    while(T--){
        scanf("%d", &n);
        for(int i = 1; i <= n; i++){
            scanf("%d", &a[i]);
        }
        Resolve();
    }

    return 0;
}

標程

#include <stdio.h>
#include <algorithm>
#define MAXN 1000005
int a[MAXN];

inline void solve(){ //inline 說明這個函數是內聯的,在編譯過程中內聯函數會直接被源代碼替換,
    //如果類中的某個函數會被調用很多次或者放在循環中,那麼建議將這個函數聲明爲內聯,可以提高程序的運行效率
    int n;
    scanf("%d",&n);
    int i;
    for (i=1;i<=n;i++) {
        scanf("%d",a+i);
    }
    int ans=std::min(2,n); // 長度爲2以上的話結果就從2開始計數,長度爲1的話結果爲1

    int l=1;
    for (i=3;i<=n;i++) {
        bool f= 2*a[i-1]==a[i-2]+a[i];
        if (!f) l=i-1;
        ans=std::max(ans,i-l+1);
    }

    l=1;
    for (i=3;i<=n;i++) {
        bool f= 1LL*a[i-1]*a[i-1]==1LL*a[i-2]*a[i]; // 1LL 轉換成long long
        if (!f) l=i-1;
        ans=std::max(ans,i-l+1);
    }

    printf("%d\n",ans);
}

int main(){
    int T;
    scanf("%d",&T);
    int i;
    for (i=1;i<=T;i++) {
        solve();
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章