跳到正文

题解

题解:P3540 [POI 2012] SQU-Squarks

违规用户名720023约 5 分钟
原文
文章信息与版本

文章信息

发布
2025年10月28日
收录
2025年12月12日
更新
2026年11月16日
篇幅
约 5 分钟
题目
P3540

版本

  1. v2当前
  2. v1

P3540 [POI 2012] SQU-Squarks

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

前情提要

前面忘了。

思路

中间忘了。

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

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

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

又我们知道 s1=x1+x2s_1 = x_1 + x_2,s2=x1+x3s_2 = x_1 + x_3,且 x2+x3x_2 + x_3 最多是第 nn 个(x1+xix_1 + x_i 可能比 x2+x3x_2 + x_3 小或大)。所以枚举 x2+x3x_2 + x_3 是 ss 第几个。

做完了。

Code

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

C++
#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;
}
原文