codevs p1006 等差数列

来源:互联网 发布:redis面试题 php 编辑:程序博客网 时间:2024/05/24 05:11

题目描述 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;}
0 0
原创粉丝点击