zcmu--2993: Fibonacci-ish(map&&枚举&&思维)

2993: Fibonacci-ish

Time Limit: 2 Sec  Memory Limit: 256 MB
Submit: 27  Solved: 12
[Submit][Status][Web Board]

Description

Yash has recently learnt about the Fibonacci sequence and is very excited about it. He calls a sequence Fibonacci-ish if

  1. the sequence consists of at least two elements
  2. f0 and f1 are arbitrary
  3. fn+2=fn+1+fn for all n≥0.

You are given some sequence of integers a1,a2,...,an. Your task is rearrange elements of this sequence in such a way that its longest possible prefix is Fibonacci-ish sequence.

Input

 The first line of the input contains a single integer n (2≤n≤1000)− the length of the sequence ai.

The second line contains n integers a1,a2,...,an (|ai|≤109).

Output

 Print the length of the longest possible Fibonacci-ish prefix of the given sequence after rearrangement.

Sample Input

3

1 2 -1

Sample Output

3

HINT

 In the first sample, if we rearrange elements of the sequence as -1, 2, 1, the whole sequence ai would be Fibonacci-ish.

【题意】给你一个序列,求该序列通过重拍后能构成斐波那契数列的最大长度。

扫描二维码关注公众号,回复: 3584196 查看本文章

【思路】使用 map。因为数组下标只能是非负数,但是输入的序列还有可能是负值,所以,不可以开数组用hash做。所以,用map吧~

  数组a记录输入的值,数组mp记录每个数字出现的次数,数组temp用于缓存一些暂时不需要的值。

注意,如果前两个数是0的时候,要特殊处理,此时比较ans与序列中0的个数就好(如果有多个0,长度必然是0的个数,如0 0 0 1 1 2不是6,因为前面的0相加是不可能得到1的);

【代码】

#include<bits/stdc++.h>
using namespace std;
const int maxn=1e3+5;
int temp[maxn],a[maxn];
map<int,int>mp;
int main()
{
	int n;
	while(~scanf("%d",&n))
	{
		mp.clear();
		memset(temp,0,sizeof(temp));
		for(int i=0;i<n;i++)
		{
			scanf("%d",&a[i]);
			mp[a[i]]++;
		}	
		int cnt,ans=2;
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<n;j++)
			{
				if(i==j)continue;
				int x=a[i],y=a[j];
				if(x==0&&y==0)
				{
					if(mp[0]>ans)ans=mp[0];
					continue;
				}
				cnt=0;
				mp[x]--,mp[y]--;//先把这两个数拿出来并存到temp数组中,避免之后重复
				temp[cnt++]=x;temp[cnt++]=y; 
				while(mp[x+y]>0)
				{
					int z=x+y;
					mp[z]--;
					temp[cnt++]=z;
					x=y;y=z;//更新x、y值 
				 } 
				for(int i=0;i<cnt;i++)
					mp[temp[i]]++;
				ans=max(ans,cnt);
			}
		}
		printf("%d\n",ans);
	}
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/qq_38735931/article/details/82758030