CF2233E2 Permutation Transmission (Difficult Version) 题解
题目大意:
对于一个 的 01 矩阵,其表示将 的排列每一个数展开为一个 位的二进制字符串,得到该矩阵。现在给你一个打乱后的 01 矩阵,问有多少种合法的复原方式。若矩阵本身不合法也请判断。
解题报告:
先看看一个按要求生成的矩阵有什么性质:
| 1 | 2 | 3 | 4 | 5 |
|---|---|---|---|---|
| 1 | 0 | 1 | 0 | 1 |
| 0 | 1 | 1 | 0 | 0 |
| 0 | 0 | 0 | 1 | 1 |
根据观察以及稍加思考,不难得到满足条件的一个矩阵
- 每一行 1 的数量非严格递增;
- 任意两列不同;
- 任意一列至少有一个 1;
- 矩阵中每一行 1 的数量构成的可重集和目标的相同。
因此,我们可以得到判断不合法情况的条件。
考虑如何计数,不妨将目标排列的二进制表看作一个集合空间,那么一个合法方案就是一个从当前集合空间到目标集合空间的一个单射。证明:要证明是单射,我们需要说明:如果两个不同的分配方案产生了相同的排列 ,这是不可能的(除非它们本来就是同一个方案)。
假设方案 A 和方案 B 产生了同一个排列 。那么它们生成的二进制矩阵必须完全相同。矩阵完全相同,意味着每一行的字符串完全相同。
如果存在两行字符串完全相同,那么在这两行对应的二进制位上,所有数字的比特值都一模一样。这在排列中会导致所有数字在这两个比特位上的组合相同,从而产生重复的列,或者产生全 的列。
但是我们之前对不合法的情况进行了特判。这个特判实际上排除了“不同行字符串相同”的情况。
因此,在通过特判的合法输入中,所有行的字符串必然两两不同。既然行字符串两两不同,那么只要分配方案不同(即某一行换了字符串),生成的矩阵就必然不同,最终的排列 也必然不同。这就证明了映射是单射。
由此,可以知道排列的顺序对答案计算不产生影响。那么合法排列 的数量就等于将打乱后的字符串分配给各行的方案数。所以答案为 ,其中 表示给定矩阵中 1 的个数为 的行的数量。
Code:
#include <stdio.h>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <unordered_map>
#include <vector>
using int64 = long long;
void MAIN() {
int n;
std::cin >> n;
int m = std::ceil(std::log2(n + 1));
std::vector<std::string> a(m + 1);
for (int i = 1; i <= m; i++) {
std::cin >> a[i];
a[i] = " " + a[i];
}
bool flg = true;
std::unordered_map<std::string, bool> ha;
for (int i = 1; i <= n; i++) {
std::string cur = "";
bool check = false;
for (int j = 1; j <= m; j++) {
cur += a[j][i];
if (a[j][i] != '0') {
check = true;
}
}
if (ha[cur] || !check) {
flg = false;
break;
}
ha[cur] = true;
}
if (!flg) {
std::cout << 0 << "\n";
return;
}
std::vector<int> cnt(n + 1);
for (int i = 1; i <= m; i++) {
int total = 0;
for (int j = 1; j <= n; j++) {
if (a[i][j] == '1') {
total++;
}
}
cnt[total]++;
}
std::vector<int> target(n + 1);
for (int i = 1; i <= m; i++) {
int total = 0;
for (int j = 1; j <= n; j++) {
if ((j >> (i - 1)) & 1) {
total++;
}
}
target[total]++;
}
for (int i = 1; i <= n; i++) {
if (target[i] != cnt[i]) {
std::cout << 0 << "\n";
return;
}
}
std::vector<int64> fact(m + 1);
fact[0] = 1;
for (int i = 1; i <= m; i++) {
fact[i] = fact[i - 1] * i;
}
int64 ans = 1;
for (int i = 1; i <= n; i++) {
if (cnt[i] != 0) {
ans *= fact[cnt[i]];
}
}
std::cout << ans << "\n";
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int t;
std::cin >> t;
while (t--) {
MAIN();
}
return 0;
}