codevs 1006 等差数列

提交地址:http://codevs.cn/problem/1006/


 

1006 等差数列

 

 时间限制: 1 s
 空间限制: 128000 KB
 题目等级 : 黄金 Gold
 
题目描述 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

 1 #include<cstdio>
 2 #include<iostream>
 3 #include<cstring>
 4 #include<algorithm>
 5 
 6 #define N 100+10
 7 
 8 using namespace std;
 9 
10 int n;
11 int a[N];
12 int ans=1;
13 int maxn=-100;
14 bool visited[N]; //防止重复搜索
15 
16 void dfs(int,int,int);
17 
18 int main()
19   {
20       scanf("%d",&n);
21       for(int i=1;i<=n;i++)
22         scanf("%d",&a[i]);
23       if(n==1||n==2)
24         {
25             printf("%d",n);
26             return 0;
27         }
28     sort(a+1,a+n+1);
29     for(int i=1;i<=n;i++)
30       for(int j=i+1;j<=n;j++)
31         {
32             dfs(j,a[j]-a[i],i);
33             if(ans>maxn)
34               maxn=ans;
35             ans=1;
36             memset(visited,0,sizeof(visited));
37         }
38       printf("%d",maxn);
39       return 0;
40   }
41   
42 void dfs(int x,int d,int last)//分别表示:搜到的位置,公差,上次的位置
43   {
44       if(x>n) return ;
45       if(visited[x]) return;
46       if(a[x]-a[last]!=d) return;
47       ans++;
48       for(int i=1;i<=n-x;i++)
49         {
50             visited[x]=true;
51             dfs(x+i,d,x);
52             visited[x]=false;//递归还原条件 
53         }
54   }

 

posted @ 2016-05-22 20:18  月沫  阅读(241)  评论(0编辑  收藏  举报