题目意思是对给定数列找出一个数,使得其2倍为另外两个数的和且后二者的下标为该数下标的一前一后。
用hash表可解。但是的确没想出来,现在观察可以发现这道题得数列是很有规律的,是1-N的数字,因此为哈希表的存储与查找提供了便利。具体细节见代码。此题参考了牛人的解法才想到可用hash,说明有时注意观察是很重要的。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<utility>
#include<string>
#include<set>
#include<vector>
#include<stack>
#include<algorithm>
#include<queue>
#include<cstdlib>
#include<cmath>
using namespace std;
const int M=10020;
bool Hash[M];
bool flag;
int n;
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
scanf("%d",&n);
getchar();
char ch;
int num;
num=0;
flag=false;
memset(Hash,0,sizeof(Hash));
while((ch=getchar())!='\n')
{
if(ch!=' ')
{
num*=10;
num+=(int)(ch-'0');
}
else
{
Hash[num]=1;
for(int j=1;j<num && j+num<=n;j++)
if(Hash[num-j]+Hash[num+j]==1) //若其中一个已经出现,另外一个没出现,则满足题意了
{
flag=true;break;
}
num=0;
}
}
Hash[num]=1;
if(flag)
printf("Y\n");
else
printf("N\n");
}
return 0;
}