本题解提供英文版,位于中文题解之后。
English version of this editorial is provided after the Chinese version.
考虑 所形成的若干个置换环,显然从前往后贪心选能选到的 最小的点。
假设目前已经贪心地选了 位,且 的取值尚未确定,则设 所在置换环长为 ,并从 开始,按 的顺序为环上每个点从 开始标号。这是因为假设 是 所在置换环上的任意一点,编号为 ,那么将 置换到 的位置上便需要 次置换。
设最优置换次数为 ,则如果在第 位填 ,则要求 。注意到这个方程不一定能成立,因为前面的贪心对 已经有了若干个限制。假设前面的限制可以合并为一个同余方程,那我们显然可以通过求 gcd 判断是否与当前方程冲突。但是这样的话需要求环长的 lcm,会爆 ___int128。
题解的解决办法是用 python 的自带高精度,但是作为 C++ 选手,我们还有另外的做法。
假设环的个数为 ,环长序列为 ,那么不可重集 的大小是 的(这是因为 )。假设第 个环对 的限制形如 ,那么有 。于是我们的本质不同方程个数便只有 个,且若新加一个方程,整个方程组解集不为空的充要条件是该方程与方程组中任意方程都有公共解,暴力判断即可。
时间复杂度 ,实际跑的非常快。
Consider the permutation cycles formed by . It is evident that we should greedily select the smallest possible from front to back.
Assume that we have already greedily selected positions, and the value of is yet to be determined. Let the length of the permutation cycle containing be , and label each point in the cycle starting from in the order of , beginning from 0. This is because if is any point in the permutation cycle containing , with a label , then moving to the position of requires permutations.
Let the optimal number of permutations be . If we fill at position , then . Note that this equation may not always hold, as the previous greedy selections have already imposed several constraints on . If the previous constraints can be combined into a single congruence equation, we can determine if it conflicts with the current equation by calculating the gcd . However, this requires calculating the lcm of the cycle lengths, which can overflow ___int128.
The solution provided in the problem uses Python’s built-in high precision, but as C++ programmers, we have another approach.
Assume there are cycles, with cycle lengths given by . The size of the unique set is (since ). Suppose the constraint on from the -th cycle is , then . Thus, the number of essentially different equations is only , and if a new equation is added, the necessary and sufficient condition for the solution set of the entire system to be non-empty is that the new equation has a common solution with every equation in the system, which can be checked by brute force.
The time complexity is , and it runs very fast in practice.