ferinの競プロ帳

競プロについてのメモ

SRM652 div1 easy ThePermutationGame

考えたこと

  • 巡回置換を何回やったら1に戻ってくるか
  • 長さNのとき周期1,2,…,Nで1にループする
  • したがってxはlcm(1,2,…,N)になる
  • x*y/gcd(x,y)を使ってlcmを求めようとするとMODでうまくいかない
  • 1~Nを素因数分解してそれぞれの素因数について出現数のmaxを数える
  • あとは積だけ計算すればいいのでMODを取りつつうまく計算できる
#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
typedef vector<int> VI;
typedef vector<VI> VVI;
typedef vector<ll> VL;
typedef vector<VL> VVL;
typedef pair<int, int> PII;

#define FOR(i, a, n) for (ll i = (ll)a; i < (ll)n; ++i)
#define REP(i, n) FOR(i, 0, n)
#define ALL(x) x.begin(), x.end()
#define IN(a, b, x) (a<=x&&x<b)
#define MP make_pair
#define PB push_back
const int INF = (1LL<<30);
const ll LLINF = (1LL<<60);
const double PI = 3.14159265359;
const double EPS = 1e-12;
const int MOD = 1000000007;
//#define int ll

template <typename T> T &chmin(T &a, const T &b) { return a = min(a, b); }
template <typename T> T &chmax(T &a, const T &b) { return a = max(a, b); }

int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};

int dp[100010];
//素数ならtrue
bool prime[1000000];

//二分累乗法 xのe乗
ll binpow(ll x, ll e) {
  ll a = 1, p = x;
  while(e > 0) {
    if(e%2 == 0) {p = (p*p) % MOD; e /= 2;}
    else {a = (a*p) % MOD; e--;}
  }
  return a % MOD;
}

class ThePermutationGame {
   public:
   int findMin(int N)
  {
    memset(prime, true, sizeof(prime));
    prime[0] = prime[1] = false;
    for (int i = 2; i * i <= 100000; i++) {
      if (prime[i]) {
        for (int j = 2 * i; j <= 100000; j += i) {
          prime[j] = false;
        }
      }
    }

    FOR(i, 1, N+1) {
      // cout << i << endl;
      if(prime[i]) {
        dp[i] = 1;
        continue;
      }
      int tmp = i;
      for(int j=2; j*j<=tmp; ++j) {
        int cnt = 0;
        while(tmp%j == 0) {
          tmp /= j;
          cnt++;
        }
        chmax(dp[j], cnt);
      }
    }

    ll ret = 1;
    FOR(i, 1, N+1) {
      (ret *= binpow(i, dp[i])) %= MOD;
    }
    return ret;
  }
};