code

· · 个人记录

#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <climits>
using namespace std;

int v1;
vector<int> arr;
int v2;
vector<vector<int>> v3;
vector<int> v4;

int func1() {
    int t1 = INT_MIN, t2 = INT_MAX;
    for (int s : v4) {
        t1 = max(t1, s);
        t2 = min(t2, s);
    }
    return t1 - t2;
}

void func2(int g1, int p1, int g2, int p2) {
    int t3 = v3[g1][p1];
    int t4 = v3[g2][p2];
    v4[g1] = v4[g1] - arr[t3] + arr[t4];
    v4[g2] = v4[g2] - arr[t4] + arr[t3];
    swap(v3[g1][p1], v3[g2][p2]);
}

int main() {
    srand((unsigned)time(0));
    cin >> v1;
    arr.resize(v1);
    for (int i = 0; i < v1; ++i) cin >> arr[i];
    v2 = v1 / 4;

    vector<int> v5(v1);
    for (int i = 0; i < v1; i++) v5[i] = i;
    sort(v5.begin(), v5.end(), [&](int x, int y) { return arr[x] < arr[y]; });
    v3.assign(v2, vector<int>(4));
    v4.assign(v2, 0);
    int l = 0, r = v1 - 1, g = 0;
    while (l < r) {
        v3[g][0] = v5[l];
        v3[g][1] = v5[l + 1];
        v3[g][2] = v5[r - 1];
        v3[g][3] = v5[r];
        v4[g] = arr[v5[l]] + arr[v5[l + 1]] + arr[v5[r - 1]] + arr[v5[r]];
        l += 2; r -= 2; g++;
    }

    int v6 = func1();
    auto v7 = v3;
    auto v8 = v4;

    const int v9 = 200000;
    for (int it = 0; it < v9; it++) {
        int t5 = rand() % v2;
        int t6 = rand() % v2;
        if (t5 == t6) continue;
        int t7 = rand() % 4;
        int t8 = rand() % 4;

        func2(t5, t7, t6, t8);
        int t9 = func1();
        if (t9 < v6) {
            v6 = t9;
            v7 = v3;
            v8 = v4;
        } else {
            func2(t5, t7, t6, t8);
        }
    }

    v3 = v7;
    for (auto &gr : v3) {
        for (int i = 0; i < 4; i++) {
            if (i > 0) cout << " ";
            cout << arr[gr[i]];
        }
        cout << "\n";
    }
    return 0;
}