Codeforces Round #673 (Div. 2) B. Two Arrays(数学)

题目链接:https://codeforces.com/contest/1417/problem/B

题意

定义 $f(a)$ 为数组 $a$ 中满足:

  • $i < j$
  • $a_i + a_j = T$

的二元组 $(i,j)$ 的个数。

试将一个大小为 $n$ 的数组 $a$ 划分为 $b,c$ 两组,使得 $f(b) + f(c)$ 最小。

题解

两数之和为 $T$ 有两种情况:

  • 一个数小于 $T$,一个数大于 $T$,此时以 $frac{T}{2}$ 为分界线分到两组即可
  • 两个数都等于 $frac{T}{2}$,此时将等于 $frac{T}{2}$ 的数轮流分到两组即可

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int t;
    cin >> t;
    while (t--) {
        int n, T;
        cin >> n >> T;
        int curMid = 0;
        for (int i = 0; i < n; i++) {
            int x;
            cin >> x;
            if (T % 2 == 0 and x == T / 2) {
                cout << (curMid++ & 1);
            } else if (2 * x < T) {
                cout << 0;
            } else {
                cout << 1;
            }
            cout << " 
"[i == n - 1];
        }
    }
    return 0;
}
原文地址:https://www.cnblogs.com/Kanoon/p/13749096.html