等差数列

题目描述 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

/*
http://codevs.cn/problem/1006/
1006 等差数列
二分查找 枚举
*/
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <map>
//#include <unordered_map>
#include <algorithm>
#include <sstream>
#include <set>
#include <iterator>

using namespace std;

#define INF 99999999
#define N 105
int n;
int a[N];

bool cmp(int x, int y)
{
    return x < y;
}

// 二分查查找
bool bearch(int x,int left,int right)
{
    if (x < a[left] || x > a[right])
        return false;
    while (left <= right)
    {
        int mid = (left + right) / 2;
        if (a[mid] == x)
            return true;
        else if (x < a[mid])
        {
            right = mid - 1;
        }
        else{
            left = mid + 1;
        }
    }
    return false;
}

set<int> settmp; // 过滤掉相同的元素

int main()
{
    freopen("in", "r", stdin);
    scanf("%d\n", &n);
    int i;
    for (i = 0; i < n;i++)
    {
        scanf("%d", &a[i]);
        settmp.insert(a[i]); // set插入
    }
    if (n == 1)
    {
        printf("1");
        return 0;
    }
    sort(a, a + n, cmp); // 从小到大排序

    // 判断连续相等的个数 相当于公差为0
    int tmpe = a[0];
    int maxC = 0;
    int tCount = 1;
    for (i = 1; i < n; i++)
    {
        if (a[i] == tmpe)
        {
            tCount++;
        }
        else{
            tmpe = a[i];
            if (tCount > maxC)
            {
                maxC = tCount;
            }
            tCount = 1;
        }
    }

    // 把a变成全都是不等的元素,即公差不为0
    set<int>::iterator it;
    n = 0;
    for (it = settmp.begin(); it != settmp.end(); it++)
    {
        a[n] = *it;
        n++;
    }
    if (n == 1)
    {
        printf("%d\n", maxC);
        return 0;
    }
    int j, k;
    for (i = 0; i < n-1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            int d = a[j] - a[i];
            for (k = 2;;k++)
            {   // 根据公差累加上去 不满足就需要判断下一个
                if (bearch(a[i]+k*d, j+1, n-1) == false)
                {
                    if (k > maxC)
                        maxC = k;
                    break;
                }
            }
        }
    }
    printf("%d\n", maxC);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值