样例:
Sample1:
6
2 1 5 2 7 4
YES
2 3 1 6
Sample2:
5
1 3 1 9 20
NO
题目大意:给出n个数字,求满足ax + ay = az + aw,(x,y,z,w不相同) 的一组数的下标。找不到就输出NO。
思路:因为ai 的范围是[1,2.5 * 106],所以ax + ay = az + aw 的范围是[2,5 * 106] ,而某个数(这里表示的是每个1~n 的ai与1~n 的aj 的加和,i != j)在此范围内出现四次则必有解。在根据鸽巢原理(很好的博客)可知,在5 * 106的范围内,想让一个数字出现四次,只需要枚举4 * 5 * 106 = 2 * 107次。
所以程序的复杂度只会有2 * 107,放心暴力。
code:
#include <algorithm>
#include <bitset>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
using namespace std;
typedef long long ll;
const int N = 5e6 + 100;
const int INF = 0x3f3f3f3f;
#define int long long
int a[N];
int I[N], J[N];//记录一下该和是被哪两个下标的数相加所得
bool check(int x, int i, int j) {
if (I[x] != i && J[x] != j && I[x] != j && J[x] != i)//判断一下x是否已经出现了两次
return true;
return false;
}
signed main(int argc, char const *argv[]) {
int n;
cin >> n;
for (int i = 1; i <= n; i++) {
cin >> a[i];
}
for (int i = 1; i <= n; i++) {//因为j是从i + 1开始的,所以和只要出现两次就满足要求,也方便记录下标
for (int j = i + 1; j <= n; j++) {
int x = a[i] + a[j];
if (!I[x]) I[x] = i;
if (!J[x]) J[x] = j;
if (check(x, i, j)) {
cout << "YES\n";
cout << I[x] << " " << J[x] << " " << i << " " << j << endl;
return 0;
}
}
}
cout << "NO\n";
return 0;
}