D - 接続容器の色配置 / Color Arrangement in Connected Containers Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
Consider a graph where the exchange devices are edges and the containers are vertices. Within each connected component, the arrangement can be changed freely while preserving the number of red liquids. Therefore, we can find the number of arrangements for each connected component using combinations and compute their product.
Analysis
Cannot Enumerate All Reachable States
Trying exchange operations in order to search for reachable color arrangements would result in an enormous number of states.
For example, if all containers are connected and the numbers of red and blue liquids are roughly equal, the number of arrangements can be as large as \(\binom{N}{\lfloor N/2\rfloor}\). Since \(N\leq 200000\), we cannot enumerate them, so we need to count the states directly.
Consider Each Connected Component
Construct a graph where containers are vertices and exchange devices are undirected edges.
A set of vertices connected to each other by paths is called a connected component. Since liquids can only move through exchanges along edges, they can never move to a different connected component.
Therefore, the number of red and blue liquids in each connected component does not change under the operations.
Liquids Can Be Rearranged Freely Within the Same Connected Component
For any two containers belonging to the same connected component, choose a path connecting them.
Let the vertices on the path be \(v_0,v_1,\ldots,v_k\). First, perform exchanges in the order:
- \((v_0,v_1),(v_1,v_2),\ldots,(v_{k-1},v_k)\)
and then in the order:
- \((v_{k-2},v_{k-1}),\ldots,(v_0,v_1)\)
This allows us to swap only the contents of the two endpoints while restoring the intermediate containers to their original states. If \(k=1\), the latter operations are unnecessary.
In other words, any two contents within the same connected component can be swapped. Thus, any arrangement is achievable as long as the number of red liquids remains the same.
Number of Arrangements in a Single Connected Component
Let \(n\) be the number of containers and \(r\) be the number of red liquids in a connected component.
The final color arrangement is uniquely determined simply by choosing which \(r\) containers will hold the red liquid. Therefore, the number of arrangements is
\(\displaystyle \binom{n}{r}=\frac{n!}{r!(n-r)!}\)
For example, if there are \(4\) containers and \(2\) red liquids, the number of arrangements is \(\binom{4}{2}=6\). Note that since liquids of the same color are indistinguishable, it is not \(4!\).
Since operations in each connected component are independent, letting the connected components be \(C_1,C_2,\ldots,C_K\), with \(n_i\) containers and \(r_i\) red liquids in each component, the answer is
\(\displaystyle \prod_{i=1}^{K}\binom{n_i}{r_i}\)
Algorithm
1. Find Connected Components Using DSU
A DSU (Disjoint Set Union / Union-Find) is a data structure that manages which group elements belong to and can merge groups efficiently.
For each exchange device \((U_j,V_j)\), perform unite(U_j - 1, V_j - 1). After processing all of them, each group in the DSU corresponds to a connected component of the graph.
2. Count the Number of Red Liquids in Each Connected Component
For each container \(i\), if S[i] == '1', add to the count of red liquids for the representative find(i) of the connected component to which that container belongs.
In the code, this count is stored in red[root]. For the number of containers in each connected component, use the size maintained by the DSU.
3. Precompute Factorials and Inverse Factorials
Let the modulus be \(P=998244353\). To compute combinations quickly, prepare the following arrays:
fact[i]: \(i! \bmod P\)inv_fact[i]: modular inverse of \(i! \bmod P\)
In modular arithmetic, instead of ordinary division, we multiply by the modular inverse. Since \(P\) is prime, by Fermat’s Little Theorem, if \(a\) is not a multiple of \(P\), then
\(a^{-1}\equiv a^{P-2}\pmod P\)
Since \(N<P\) here, the modular inverse of \(N!\) exists. First, compute
\(\text{inv\_fact}[N]=\text{fact}[N]^{P-2}\bmod P\)
using repeated squaring. Then, compute the remaining inverse factorials for \(i=N,N-1,\ldots,1\) in descending order by
\(\text{inv\_fact}[i-1]=\text{inv\_fact}[i]\times i\bmod P\)
This allows us to compute each combination in \(O(1)\) time as
\(\displaystyle \binom{n}{r}\equiv \text{fact}[n]\times\text{inv\_fact}[r]\times\text{inv\_fact}[n-r]\pmod P\)
4. Multiply the Number of Arrangements for Each Connected Component
Initialize the answer to \(1\), and iterate over only the representatives of the DSU.
For each connected component, with size being the number of containers and red[root] being the number of red liquids, multiply the answer by \(\binom{\text{size}}{\text{red[root]}}\) and take the modulo \(P\) each time.
Complexity
- Time complexity: \(O((N+M)\alpha(N)+\log P)\)
- Space complexity: \(O(N)\)
Here, \(P=998244353\), and \(\alpha(N)\) is the inverse Ackermann function, which is practically constant. The DSU operations take \(O((N+M)\alpha(N))\) time, and precomputing factorials and inverse factorials takes \(O(N+\log P)\) time.
Since edges are incorporated into the DSU upon input, there is no need to store all of them.
Implementation Details
Convert vertex indices to 0-based
The container indices in the input are 1-based, but arrays are 0-based, so subtract \(1\) when passing them tounite.Count the number of red liquids after all merges are complete
The representatives in the DSU can change upon merging. In the code,redis aggregated after processing all devices.The size is also stored in the DSU array
Ifp[i] < 0, then \(i\) is a representative, and-p[i]is the size of the connected component. Non-representative elements are excluded from the answer calculation.No special handling needed for self-loops or multi-edges
Callinguniteon elements already in the same group does nothing, so they can be processed as-is.Include index 0 for factorials
There may be \(0\) red liquids or all red liquids. By setting \(0!=1\), the number of arrangements correctly evaluates to \(1\) in both cases.Use
long longfor multiplication
The product before taking the modulo exceeds the range of a 32-bit integer. Use 64-bit integers as in the code, and take the modulo immediately after each multiplication.Source Code
#include <bits/stdc++.h>
using namespace std;
constexpr long long MOD = 998244353;
struct DSU {
vector<int> p;
explicit DSU(int n) : p(n, -1) {}
int find(int x) {
return p[x] < 0 ? x : p[x] = find(p[x]);
}
void unite(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return;
if (p[a] > p[b]) swap(a, b);
p[a] += p[b];
p[b] = a;
}
};
long long mod_pow(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;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N, M;
cin >> N >> M;
string S;
cin >> S;
DSU dsu(N);
for (int i = 0; i < M; ++i) {
int u, v;
cin >> u >> v;
dsu.unite(u - 1, v - 1);
}
vector<int> red(N, 0);
for (int i = 0; i < N; ++i) {
if (S[i] == '1') ++red[dsu.find(i)];
}
vector<long long> fact(N + 1), inv_fact(N + 1);
fact[0] = 1;
for (int i = 1; i <= N; ++i) {
fact[i] = fact[i - 1] * i % MOD;
}
inv_fact[N] = mod_pow(fact[N], MOD - 2);
for (int i = N; i >= 1; --i) {
inv_fact[i - 1] = inv_fact[i] * i % MOD;
}
long long answer = 1;
for (int i = 0; i < N; ++i) {
if (dsu.p[i] >= 0) continue;
int size = -dsu.p[i];
answer = answer * fact[size] % MOD;
answer = answer * inv_fact[red[i]] % MOD;
answer = answer * inv_fact[size - red[i]] % MOD;
}
cout << answer << '\n';
return 0;
}
This editorial was generated by gpt-6-astra-medium.
posted:
last update: