题目链接:https://codeforces.com/contest/1501/problem/C
It was the third month of remote learning, Nastya got sick of staying at dormitory, so she decided to return to her hometown. In order to make her trip more entertaining, one of Nastya’s friend presented her an integer array a.
Several hours after starting her journey home Nastya remembered about the present. To entertain herself she decided to check, are there four different indices x,y,z,w such that ax+ay=az+aw.
Her train has already arrived the destination, but she still hasn’t found the answer. Can you help her unravel the mystery?
Input
The first line contains the single integer n (4≤n≤200000) — the size of the array.
The second line contains n integers a1,a2,…,an (1≤ai≤2.5⋅106).
Output
Print “YES” if there are such four indices, and “NO” otherwise.
If such indices exist, print these indices x, y, z and w (1≤x,y,z,w≤n).
If there are multiple answers, print any of them.
Examples
input
6
2 1 5 2 7 4
output
YES
2 3 1 6
input
5
1 3 1 9 20
output
NO
分析
经过同学点拨,豁然开朗。
将式子转化一下,ax - aw = az - ay ,发现只需要找到差相同的两对数即可,在最坏的情况下,没有这样符合的数列可以是:1,2,4,7,11……
根据题目的 ai ≤ 2.5 * 10^6 ,最多只能有不到 3000 项,那么我们先排序,对于 3000 项目以内的序列,我们可以直接用 n^2 的复杂的暴力算出,若大于 3000 项,从后往前找肯定会有符合要求的。
代码
#include<bits/stdc++.h>
using namespace std;
const int N=2e5+10,M=5e6+10;
pair<int,int>a[N];
map<int,int>vis;
int xx[M],yy[M];
int main()
{
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a[i].first);
a[i].second=i;
}
sort(a+1,a+1+n);
if(n<=3e3)
{
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
int p=a[i].first+a[j].first;
vis[p]++;
if(vis[p]==1)
{
xx[p]=a[i].second;
yy[p]=a[j].second;
}
else
{
if(xx[p]!=a[i].second&&xx[p]!=a[j].second&&yy[p]!=a[i].second&&yy[p]!=a[j].second)
{
printf("YES\n");
printf("%d %d %d %d\n",xx[p],yy[p],a[i].second,a[j].second);
return 0;
}
}
}
}
}
else
{
for(int i=n;i>1;i--)
{
int d;
d=a[i].first-a[i-1].first;
vis[d]++;
if(vis[d]==1) xx[d]=i;
else
{
if(i+1!=xx[d])
{
printf("YES\n");
printf("%d %d %d %d\n",a[i-1].second,a[xx[d]].second,a[i].second,a[xx[d]-1].second);
return 0;
}
}
}
}
printf("NO\n");
return 0;
}