Codeforces Round #707 (Div. 2)C.Going Home (鸽巢原理)

题目链接


在这里插入图片描述

样例:
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;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值