题解:P3540 [POI 2012] SQU-Squarks

· · 题解

P3540 [POI 2012] SQU-Squarks

双倍经验 P1286,额外判个无解,再允许含有零的情况即可。

前情提要

前面忘了。

思路

中间忘了。

对 s 和 x 定序,这里的顺序需要相同,不能 s 降 x 升或者 s 升 x 降。

假设你知道 x_1, \cdots x_k 那么你就可以知道 x_{k + 1},因为这样你可以知道在 x_1 到 x_k 之间的数的两两之和,把它们去除,于是剩下里面最小的(或者最大的,取决你的定序方式)就是 x_1 + x_{k + 1}。

所以如果你知道第一个数是 x_1 那么你可以通过它推出后面的所有数。

又我们知道 s_1 = x_1 + x_2,s_2 = x_1 + x_3,且 x_2 + x_3 最多是第 n 个(x_1 + x_i 可能比 x_2 + x_3 小或大)。所以枚举 x_2 + x_3 是 s 第几个。

做完了。

Code

这里使用 gp_hash_table 来完成“去除”操作。

#include <iostream>
#include <algorithm>
#include <queue>
#include <ext/pb_ds/hash_policy.hpp>
#include <ext/pb_ds/assoc_container.hpp>
#define int long long
using namespace std;
using namespace __gnu_pbds;
int n, cnt;
int s[100010];
int x[310][100010];
int tx[310], cur;
gp_hash_table<int, int> mp;
bool cmp(int x, int y) {
    return x > y;
}
signed main() {
    cin >> n;
    for(int i = 1; i <= n * (n - 1) / 2; i++) {
        cin >> s[i];
    }
    sort(s + 1, s + n * (n - 1) / 2 + 1, cmp);
    for(int i = 3; i <= n; i++) {
        if(s[i] == s[i - 1] && i != 3) continue;
        int sum = s[1] + s[2] + s[i];
        if(sum & 1) continue;
        sum >>= 1;
        if(sum - s[1] <= 0 || sum - s[i] <= 0 || sum - s[2] <= 0) continue;
        cur = 0;
        tx[++cur] = sum - s[i];
        tx[++cur] = sum - s[2];
        tx[++cur] = sum - s[1];
        if(tx[1] == tx[2] || tx[2] == tx[3]) continue;
        mp.clear();
        for(int j = 1; j <= n * (n - 1) / 2; j++) mp[s[j]]++;
        mp[s[1]]--;
        mp[s[2]]--;
        mp[s[i]]--;
        bool f = 1;
        for(int j = 3; j <= n * (n - 1) / 2; j++) {
            if(mp.find(s[j]) == mp.end() || mp[s[j]] == 0) continue;
            tx[++cur] = s[j] - tx[1];
            //cerr << j << ' ' << s[j] << '\n';
            if(tx[cur] <= 0 || tx[cur] >= tx[cur - 1]) {
                f = 0;
                break;
            }
            for(int k = 1; k <= cur - 1; k++) {
                if(mp.find(tx[cur] + tx[k]) == mp.end() || mp[tx[cur] + tx[k]] == 0) {
                    f = 0;
                    break;
                }
                mp[tx[cur] + tx[k]]--;
            }
            if(f == 0) break;
        }
//      cerr << cur << ' ' << f << '\n';
//      for(int j = 1; j <= cur; j++) cerr << tx[j] << ' ';
//      cerr << '\n';
        if(cur < n) f = 0;
        if(f) {
            cnt++;
            for(int j = 1; j <= n; j++) {
                x[cnt][n - j + 1] = tx[j];
            }
        }
    }
    cout << cnt << '\n';
    for(int i = cnt; i >= 1; i--) {
        for(int j = 1; j <= n; j++) cout << x[i][j] << ' ';
        cout << '\n';
    }
    return 0;
}