题解:CF2227C Snowfall

· · 题解

题意

给你一个数组,你可以任意重排。求一种排列,使得元素乘积能被 6 整除的子数组个数最少,并输出这个排列。

分析

乘积能被 6 整除子数组中至少有一个 2 的倍数 且 至少有一个 3 的倍数。

为了最小化这样的子数组,我们应让 2 的倍数和 3 的倍数尽量不重叠出现。

构造方法

这样会把 2 和 3 的主要集中区域分开,让同时包含 2 和 3 的子数组最少。

代码

#include <bits/stdc++.h>
using namespace std;
int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<int> a1, a2, a3, a4;
        for (int i = 0; i < n; i++) {
            int x;
            cin >> x;
            if (x % 6 == 0) a1.push_back(x);
            else if (x % 2 == 0) a2.push_back(x);
            else if (x % 3 == 0) a3.push_back(x);
            else a4.push_back(x);
        }
        for (int x : a1) cout << x << " ";
        for (int x : a2) cout << x << " ";
        for (int x : a4) cout << x << " ";
        for (int x : a3) cout << x << " ";
        cout << "\n";
    }
    return 0;
}

为什么这样构造