题解:CF2164B Even Modulo Pair

· · 题解

如果有至少两个偶数,显然任意两个偶数的模都是偶数,输出它们即可。

如果有一个偶数,我们尝试将其与每一个奇数配对。

如果没有偶数或上一种情况无解:

首先,我们处理出全部都是奇数的数组。

当后一个数不大于前一个数的两倍时,后一个数模前一个数的值为后一个数与前一个数的差。而两个奇数的差显然是偶数,所以当存在满足上述条件的项时,O(N) 复杂度对数组进行扫描即可。

否则,由于每个数都至少是前一个数的两倍以上,且 a_i \leq 10^9,数组里最多会有 \lfloor \log_2{10^9} \rfloor + 1 = 30 个数,此时 O(N^2) 暴力即可。

代码:

#include <bits/stdc++.h>
using namespace std;

int a[200005], b[200005];

void solve()
{
    int n, m = 0;
    cin >> n;
    int even = 0;
    int c = 0, d = 0;
    for (int i = 1; i <= n; ++i) {
        cin >> a[i];
        if (a[i] % 2 == 0) {
            ++even;
            d = c, c = a[i];
        } else {
            b[++m] = a[i];
        }
    }
    if (even >= 2) {
        cout << d << " " << c << endl;
        return;
    } else if (even == 1) {
        for (int i = 1; i <= m; ++i) {
            if (b[i] < c && (c % b[i]) % 2 == 0) {
                cout << b[i] << " " << c << endl;
                return;
            }
            if (c < b[i] && (b[i] % c) % 2 == 0) {
                cout << c << " " << b[i] << endl;
                return;
            }
        }
    }
    {
        if (n <= 35) {
            for (int i = 1; i <= n; ++i) {
                for (int j = 1; j <= n; ++j) {
                    if (a[i] > a[j] && a[i] % a[j] % 2 == 0) {
                        cout << a[j] << " " << a[i] << endl;
                        return;
                    }
                }
            }
        } else {
            for (int i = 1; i <= n - 1; ++i) {
                if (a[i + 1] > a[i] && a[i + 1] % a[i] % 2 == 0) {
                    cout << a[i] << " " << a[i + 1] << endl;
                    return;
                }
            }
        }
    }
    cout << -1 << endl;
}

int main()
{
    int t;
    cin >> t;
    while (t--) {
        solve();
    }
}