D - 接続容器の色配置 / Color Arrangement in Connected Containers Editorial by admin Editorial for printing
gpt-6-astra-mediumOverview
Consider a graph where containers are vertices and exchange devices are edges. We can find the answer by counting the number of ways to choose which containers hold the red liquid within each connected component, and then multiplying these counts together across all components.
Analysis
1. Considering Each Connected Component Independently
Containers directly connected by a device can have their contents swapped. Furthermore, even if two containers are not directly connected, liquid can be moved between them as long as there is a path of devices connecting them.
On the other hand, liquid cannot be moved between different connected components. Therefore, the number of red liquids contained in each connected component is invariant under the operations.
Thus, it suffices to count the number of possible configurations for each connected component independently.
2. Arbitrary Permutations Within the Same Connected Component
Consider any two containers belonging to the same connected component. Let the path connecting them be
\(v_0, v_1, \ldots, v_k\).
First, perform swaps along the path in the order of
\((v_0,v_1), (v_1,v_2), \ldots, (v_{k-1},v_k)\).
Then, perform swaps in the order of
\((v_{k-2},v_{k-1}), \ldots, (v_0,v_1)\).
This restores the contents of all intermediate containers to their original states, while only swapping the contents of the two endpoints. (Note that when \(k=1\), the second set of swaps is unnecessary.)
In this way, any two containers in the same connected component can be swapped. Since any permutation can be achieved by repeatedly swapping two elements, any configuration within the same connected component is achievable as long as the number of red liquids remains the same.
3. Number of Configurations for a Single Component is a Binomial Coefficient
Let \(k\) be the number of containers in a connected component, and let \(r\) be the number of red liquids in it.
The final state of this component is determined by “which \(r\) out of the \(k\) containers will hold red liquid.” Therefore, the number of configurations is
\(\displaystyle \binom{k}{r}=\frac{k!}{r!(k-r)!}\).
For example, if there are \(4\) containers and \(2\) of them contain red liquid, the number of configurations is \(\binom{4}{2}=6\). Note that liquids of the same color are indistinguishable, so it is not \(4!\).
Since the configuration of each connected component can be chosen independently, the answer is
\(\displaystyle \prod_{\text{connected component }C}\binom{|C|}{r_C}\),
where \(r_C\) is the number of red liquids contained in connected component \(C\).
4. Do Not Enumerate Configurations Directly
If we were to enumerate all color configurations, there could be up to \(2^N\) candidates. Searching for states reachable by operations would also not finish in time because the number of states is extremely large.
Therefore, we utilize the following two techniques:
- Use a Union-Find to manage the connected components, along with their container counts and red liquid counts.
- Precompute factorials and inverse factorials to compute binomial coefficients quickly.
Algorithm
1. Initialize the Union-Find
Initially, each container forms its own independent connected component.
In the code, we use the following arrays:
parent[i]- If
iis a root, it stores the negative of the component’s container count. - If
iis not a root, it stores the vertex index of its parent.
- If
red[i]- When
iis a root, it stores the number of red liquids contained in that component.
- When
In the initial state, set parent[i] = -1, and set red[i] to \(1\) if the corresponding character is 1, or \(0\) if it is 0.
2. Merge Components Connected by Each Device
For each edge \((U_j,V_j)\), find the roots of the components to which the endpoints belong.
- If the roots are the same, do nothing.
- If the roots are different, merge the two components:
- Sum up the container counts.
- Sum up the counts of red liquids.
By attaching the smaller component to the larger one, we prevent the tree from becoming deep.
3. Collect Components for Which to Calculate Configurations
Check all roots and extract the container count \(k\) and the red liquid count \(r\).
A component with \(r=0\) or \(r=k\) has all containers of the same color, so there is only \(1\) configuration. Such components can be excluded from the calculation.
If no components remain to be calculated, the answer is \(1\).
4. Precompute Factorials and Inverse Factorials
Let \(L\) be the maximum size among the components to be calculated. For each \(i\) from \(0\) to \(L\), compute the following:
- \(\mathrm{fact}[i]=i!\bmod P\)
- \(\mathrm{inv\_fact}[i]=(i!)^{-1}\bmod P\)
where \(P=998244353\).
When computing modulo, instead of ordinary division, we must multiply by the modular inverse. Since \(P\) is prime and \(L\le N<P\), by Fermat’s Little Theorem, we can compute
\(\mathrm{inv\_fact}[L]=\mathrm{fact}[L]^{P-2}\bmod P\).
After that, compute them in descending order using:
\(\mathrm{inv\_fact}[i-1]=\mathrm{inv\_fact}[i]\times i\bmod P\).
5. Multiply the Number of Configurations of Each Component
For each component’s \((k,r)\), compute
\(\displaystyle \binom{k}{r}\bmod P =\mathrm{fact}[k]\times\mathrm{inv\_fact}[r]\times\mathrm{inv\_fact}[k-r]\bmod P\)
and multiply it into the total answer.
Since the positions of red liquids can be chosen arbitrarily within each connected component, and the configurations across different connected components can be chosen independently, this product is the desired answer.
Complexity
- Time complexity: \(O((N+M)\alpha(N)+\log P)\)
- Space complexity: \(O(N)\)
where \(\alpha(N)\) is the inverse Ackermann function, which is practically constant. The \(\log P\) term comes from modular exponentiation (repeated squaring) to compute the modular inverse.
Since edges can be processed directly upon input, there is no need to store all edges.
Implementation Details
Container indices in the input are \(1\)-based, so subtract \(1\) to convert them to \(0\)-based indexing for the Union-Find.
For a root,
parentstores the negative of the component size. Therefore, a smaller value indicates a larger component.The value of
redis only referenced for roots. When merging, add the count of red liquids to the new root.Self-loops and multiple edges can be naturally handled by skipping the operation if the roots of both endpoints are the same.
In the code,
sis of typebytes. Iterating over it yields character codes, soc - 48converts'0'and'1'to integers.Take the modulo after every multiplication to prevent values from becoming too large.
Source Code
import sys
MOD = 998244353
def main():
readline = sys.stdin.buffer.readline
n, m = map(int, readline().split())
s = readline().strip()
parent = [-1] * n
red = [c - 48 for c in s]
def find(x):
while parent[x] >= 0:
p = parent[x]
if parent[p] >= 0:
parent[x] = parent[p]
x = parent[x]
return x
for _ in range(m):
u, v = map(int, readline().split())
u = find(u - 1)
v = find(v - 1)
if u == v:
continue
if parent[u] > parent[v]:
u, v = v, u
parent[u] += parent[v]
parent[v] = u
red[u] += red[v]
components = [
(-parent[i], red[i])
for i in range(n)
if parent[i] < 0 and 0 < red[i] < -parent[i]
]
if not components:
print(1)
return
limit = max(size for size, _ in components)
fact = [1] * (limit + 1)
for i in range(2, limit + 1):
fact[i] = fact[i - 1] * i % MOD
inv_fact = [1] * (limit + 1)
inv_fact[limit] = pow(fact[limit], MOD - 2, MOD)
for i in range(limit, 0, -1):
inv_fact[i - 1] = inv_fact[i] * i % MOD
answer = 1
for size, count in components:
answer = answer * fact[size] % MOD
answer = answer * inv_fact[count] % MOD
answer = answer * inv_fact[size - count] % MOD
print(answer)
if __name__ == "__main__":
main()
This editorial was generated by gpt-6-astra-medium.
posted:
last update: