D - 接続容器の色配置 / Color Arrangement in Connected Containers Editorial by admin Editorial for printing
importedOverview
We want to find the number of possible color configurations that can be obtained by repeatedly swapping the contents of two connected containers. For each connected component of the graph where swap devices are edges, we count the number of ways to choose which containers will hold the red liquid.
Analysis
Since there is no upper bound on the number of operations, we cannot try all possible sequences of operations. Moreover, even if we explore states by only recording color configurations, there can be up to \(2^N\) candidates. Let us consider the condition for a color configuration to be reachable.
We construct a graph where containers are vertices and swap devices are undirected edges. Since each swap only occurs within the same connected component, the number of red liquids contained in each connected component remains invariant.
Any Two Containers in the Same Connected Component Can Be Swapped
Let \(x_0, x_k\) be two distinct vertices in the same connected component, and let \(x_0, x_1, \ldots, x_k\) be a simple path connecting them. Along this path, we first perform swaps in the order of edges \((x_0,x_1), (x_1,x_2), \ldots, (x_{k-1},x_k)\). As a result, the original contents of \(x_0\) reach \(x_k\).
Next, we perform swaps in the order of edges \((x_{k-2},x_{k-1}), \ldots, (x_0,x_1)\). After this, the original contents of \(x_k\) move to \(x_0\), and the contents of all intermediate vertices return to their initial states. If \(k=1\), the second half of the operations is omitted.
Therefore, we can swap only the contents of any two containers within the same connected component without altering the rest. Repeating this allows us to move the red liquids within a component to any subset of containers of the same size. For example, among the containers whose colors differ from the target configuration, we can pick a pair of containers where one is currently red and target blue, while the other is currently blue and target red; swapping them makes both match their target colors. As long as the total number of red liquids is the same, such a pair of containers always exists.
Thus, the necessary and sufficient condition for reachability is that the number of red liquids in each connected component equals that of the initial state.
Counting the Configurations
For a component with \(s\) vertices that initially contains \(r\) vertices with red liquid, choosing which \(r\) vertices will be red uniquely determines the configuration. The number of such choices is \(\binom{s}{r}\). Since operations and configurations in different components are independent, the overall answer is the product of the binomial coefficients over all components.
Let \(P=998244353\). Since \(s\leq N<P\), \(s!\) and its divisors have modular inverses modulo \(P\). By precomputing factorials and inverse factorials,
\[ \binom{s}{r}=s!\,(r!)^{-1}\,((s-r)!)^{-1}\pmod P \]
can be computed in constant time per component. Inverse factorials can be computed in descending order using \((i-1)!^{-1}=i\,(i!)^{-1}\bmod P\) after computing \((N!)^{-1}=(N!)^{P-2}\bmod P\) once via Fermat’s Little Theorem.
Algorithm
- Initialize a Union-Find data structure, and unite the endpoints of each swap device.
- Find the representative of each vertex, and tally the count of red liquids for each component. The number of vertices in each component can be obtained from the component sizes stored in the Union-Find structure.
- Precompute factorials and inverse factorials from \(0!\) to \(N!\).
- For the size \(s\) and number of reds \(r\) of each component, compute \(\binom{s}{r}\) and multiply it into the answer, taking the modulo at each step.
- Output the final answer.
The components found by Union-Find are precisely the connected components formed by the swap devices. By the necessary and sufficient condition shown above, the valid final configurations of a component correspond exactly to the choice of red positions. Multiplying once for each component ensures that no configurations are missed or double-counted.
Complexity
Let \(N\) be the number of containers, \(M\) be the number of swap devices, and \(P=998244353\).
The time complexity is \(O((N+M)\alpha(N)+\log P)\), where \(\alpha\) is the inverse Ackermann function, representing the amortized time complexity of Union-Find with union by size and path compression. Precomputing factorials and tallying counts take \(O(N)\), and a single modular exponentiation takes \(O(\log P)\).
The space complexity is \(O(N)\). We store the Union-Find structure, the counts of red liquids, factorials, inverse factorials, and the color string, while swap devices are processed as they are read.
Implementation Notes
Devices that connect the same container or connect containers already in the same component do not change anything upon uniting. Isolated containers are also counted as components of size \(1\), and their contribution is \(1\).
Modular multiplications are performed two values at a time. Since the product satisfies \(P^2<2^{63}\), it fits within a signed 64-bit integer. Cases where the number of red liquids is \(0\) or equal to the component size are also correctly handled by the formula using \(0!=1\).
Source Code
#include <bits/stdc++.h>
using namespace std;
const long long MOD = 998244353;
long long power(long long a, long long e) {
long long result = 1;
while (e > 0) {
if (e & 1) result = result * a % MOD;
a = a * a % MOD;
e >>= 1;
}
return result;
}
struct DSU {
vector<int> parent;
explicit DSU(int n) : parent(n, -1) {}
int leader(int v) {
int r = v;
while (parent[r] >= 0) r = parent[r];
while (v != r) {
int next = parent[v];
parent[v] = r;
v = next;
}
return r;
}
void merge(int u, int v) {
u = leader(u);
v = leader(v);
if (u == v) return;
if (parent[u] > parent[v]) swap(u, v);
parent[u] += parent[v];
parent[v] = u;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
string s;
cin >> n >> m >> s;
DSU dsu(n);
for (int i = 0; i < m; ++i) {
int u, v;
cin >> u >> v;
dsu.merge(u - 1, v - 1);
}
vector<int> red(n, 0);
for (int v = 0; v < n; ++v) {
red[dsu.leader(v)] += s[v] - '0';
}
vector<long long> fact(n + 1, 1), inverse_fact(n + 1, 1);
for (int i = 1; i <= n; ++i) fact[i] = fact[i - 1] * i % MOD;
inverse_fact[n] = power(fact[n], MOD - 2);
for (int i = n; i >= 1; --i) inverse_fact[i - 1] = inverse_fact[i] * i % MOD;
long long answer = 1;
for (int v = 0; v < n; ++v) {
if (dsu.parent[v] < 0) {
int size = -dsu.parent[v];
long long ways = fact[size] * inverse_fact[red[v]] % MOD;
ways = ways * inverse_fact[size - red[v]] % MOD;
answer = answer * ways % MOD;
}
}
cout << answer << '\n';
return 0;
}
This editorial was generated by imported.
posted:
last update: