Codeforces Round #334 (Div. 2) D. Modular Arithmetic(置換)

題意:給出方程 f(kx%p)=kf(x)%p ,問在集合A->B上不同的映射函數f有幾種,其中A=B={0,1,2..p-1},p爲素數(除了2),k爲小於p的一個常數。

思路:f(kx1%p) = kf(x0)%p,

f(kx2%p) = kf(x1)%p = k^2 * f(x0)%p,

f(kx3%p) = ... = k^3 * f(x0)%p,

......

f(kxm%p) = ... = k^m * f(x0)%p.

顯然,由於gcd(k, p) == 1,由費馬小定理最終一定存在m使得k^m % p == 1,且m爲p-1的因子。這樣就形成了環。對每個環,起始位置有p種可能,所以 ans = p ^ cnt。特判k爲0和1的情況。

#include <algorithm>
#include <iostream>
#include <sstream>
#include <cstring>
#include <cstdio>
#include <vector>
#include <string>
#include <queue>
#include <stack>
#include <cmath>
#include <set>
#include <map>
using namespace std;

typedef long long LL;
#define mem(a, n) memset(a, n, sizeof(a))
#define ALL(v) v.begin(), v.end()
#define si(a) scanf("%d", &a)
#define sii(a, b) scanf("%d%d", &a, &b)
#define siii(a, b, c) scanf("%d%d%d", &a, &b, &c)
#define pb push_back
#define eps 1e-8
const int inf = 0x3f3f3f3f, N = 1e6 + 5, MOD = 1e9 + 7;

int T, cas = 0;
bool vis[N];
LL p, k;
LL quick_mod(LL a, LL b, LL m) {
    LL ret = 1;
    a %= m;
    while(b > 0) {
        if(b & 1) ret = ret * a % m;
        a = a * a % m;
        b >>= 1;
    }
    return ret;
}

int main(){
#ifdef LOCAL
    freopen("/Users/apple/input.txt", "r", stdin);
//	freopen("/Users/apple/out.txt", "w", stdout);
#endif
    
    cin >> p >> k;
    if(k == 0) {
        cout << quick_mod(p, p - 1, MOD) << endl;
        return 0;
    } if(k == 1) {
        cout << quick_mod(p, p, MOD) << endl;
        return 0;
    }
    mem(vis, false);
    LL ans = 1; int cnt = 0;
    for(int i = 0; i < p; i ++) {
        int idx = i, flag = 0;
        while(!vis[idx]) {
            vis[idx] = 1; flag ++;
            idx = 1LL * idx * k % p;
        }
        cnt += flag > 1;
    }
    cout << quick_mod(p, cnt, MOD) << endl;
    return 0;
}


發佈了115 篇原創文章 · 獲贊 3 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章