題目描述 Description
給定n(1<=n<=100)個數,從中找出儘可能多的數使得他們能夠組成一個等差數列.求最長的等差數列的長度.
輸入描述 Input Description
第一行是一個整數n,接下來一行包括了n個數,每個數的絕對值不超過10000000.
輸出描述 Output Description
對於每個輸入數據,輸出你所找出的最長等差數列的長度
樣例輸入 Sample Input
7
3
8
4
5
6
2
2
樣例輸出 Sample Output
5
題解
大多數人第一眼看到這個題都會先想到從小到大排序,然後dp,但是公差太大會炸掉(雖然還是有好多神犇用dp並且a掉了,不過我太水了),然後發現n只有100,所以我們考慮用暴力一點的辦法搞它。從小到大排序後枚舉答案等差數列的起點及公差,然後從1到n掃一遍。枚舉公差時注意,因爲公差可能很大,但n很小,所以我們可以在枚舉到首項爲a[i]時,把a[j]-a[I](j>i)當作公差。
代碼
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
using namespace std;
int dp[150][150];
int a[150], b[150], sum[150];
int n;
int main() {
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &a[i]);
sort(a+1, a+1+n);
int ans = -1;
for(int i = 1; i <= n; i++)
for(int j = i+1; j <= n; j++){
int num = 1;
int c = a[j] - a[i];
for(int k = j+1; k <= n; k++) {
int c2 = a[k] - a[j];
if(c != 0 && (c2 % c == 0) && (c2 / c == num)) num++;
}
ans = max(ans, num);
}
printf("%d", ans+1);
return 0;
}