G - YY's new problem(HUSH算法,目前还不懂什么是HUSH算法)

判断等差数列元素存在性
本文介绍了一个算法问题,即给定1到N的一个排列P,如何判断是否存在三个元素P[i1], P[i2], P[i3]形成等差数列。通过两次遍历数组并利用哈希表快速查找中间项位置的方法来解决该问题。
 
Time Limit:4000MS     Memory Limit:65536KB     64bit IO Format:%I64d & %I64u

Description

Given a permutation P of 1 to N, YY wants to know whether there exists such three elements P[i 1], P[i 2], P[i 3] that
P[i 1]-P[i 2]=P[i 2]-P[i 3], 1<=i 1<i 2<i 3<=N.
 

Input

The first line is T(T<=60), representing the total test cases.
Each test case comes two lines, the former one is N, 3<=N<=10000, the latter is a permutation of 1 to N.
 

Output

For each test case, just output 'Y' if such i 1, i 2, i 3 can be found, else 'N'.
 

Sample Input

2 3 1 3 2 4 3 2 4 1
 

Sample Output

N Y
 
 1 #include<cstdio>
 2 #include<string.h>
 3 using namespace std;
 4 int hush[10005];
 5 int str[10005];
 6 int main()
 7 {
 8     int t,n;
 9     while(scanf("%d",&t)!=EOF)
10     {
11         while(t--)
12         {
13             scanf("%d",&n);
14             for(int i=1; i<=n; i++)
15             {
16                 scanf("%d",&str[i]);//把1——N保存到数组里
17                 hush[str[i]]=i;//记录每个数的位置
18             }
19             int flag=0;
20             for(int i=1; i<=n; i++)
21             {
22                  for(int j=i+1; j<=n; j++)
23                 {
24                    int temp=str[i]+str[j];//相加
25                    if(temp%2)//优化,必须是偶数才行,尽量别写成temp%2==1,直接写temp%2
26                      continue;
27                    if(hush[temp/2]>i&&hush[temp/2]<j)
28                    {
29                        flag=1;
30                        break;
31                    }
32                 }
33                 if(flag==1) break;
34             }
35             printf("%c",flag==1?'Y':'N');
36             printf("\n");
37         }
38     }
39     return 0;
40 }

 

 

转载于:https://www.cnblogs.com/angledamon/p/3894128.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值