2020牛客暑期多校训练营(第二场)J.Just Shuffle(逆元+模拟)

J-Just Shuffle

题意:给定一个排列A和一个大质数k,找出一个置换B,使得P经过k次B置换后得到A,输出第一次置换后的结果
题解:在排列A上找出所有环,记环的大小为 s z i sz_{i} szi,每一步移动的长度为 t m p i tmp_{i} tmpi,使得 t m p i ∗ k ≡ 1 m o d s z i tmp_{i}*k\equiv1 mod sz_{i} tmpik1modszi,也就是求出k在 m o d s z i modsz_{i} modszi下的逆元,k为大质数,所以一定有解,输出每个环移动 t m p i tmp_{i} tmpi之后的结果

Code:

#include 
using namespace std;
#define ll long long
#define db double
#define pii pair
#define pdd pair
#define mem(a, b) memset(a, b, sizeof(a));
#define lowbit(x) (x & -x)
#define lrt nl, mid, rt << 1
#define rrt mid + 1, nr, rt << 1 | 1
template <typename T>
inline void read(T& t) {
    t = 0;
    int f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-')
            f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        t = t * 10 + ch - '0';
        ch = getchar();
    }
    t *= f;
}
const int dx[] = {0, 1, 0, -1};
const int dy[] = {1, 0, -1, 0};
const ll Inf = 0x7f7f7f7f7f7f7f7f;
const int inf = 0x7f7f7f7f;
const db eps = 1e-5;
const db Pi = acos(-1);
const int maxn = 1e5 + 10;

int an[maxn];
int vis[maxn];
int res[maxn];
vector<int> vt;

int main(void) {
    int n;
    ll k;
    read(n), read(k);
    for (int i = 1; i <= n; i++)
        read(an[i]);
    for (int i = 1; i <= n; i++) {
        if (vis[i])
            continue;
        int pos = i;
        vt.clear();
        while (!vis[pos]) {
            vis[pos] = 1;
            vt.push_back(pos);
            pos = an[pos];
        }
        int sz = vt.size();
        int tmp = 0;
        while (tmp < sz) { //当sz等于1时,相当于自环,不移动
            if ((ll)tmp * k % sz == 1) //计算逆元
                break;
            tmp++;
        }
        for (int i = 0; i < sz; i++)
            res[vt[i]] = vt[(i + tmp) % sz];
    }
    for (int i = 1; i <= n; i++)
        printf("%d ", res[i]);
    return 0;
}

你可能感兴趣的:(数学,牛客多校,模拟)