1. 程式人生 > >cf121C. Lucky Permutation(康託展開)

cf121C. Lucky Permutation(康託展開)

題意

題目連結

Sol

由於階乘的數量增長非常迅速,而\(k\)又非常小,那麼顯然最後的序列只有最後幾位會發生改變。

前面的位置都是\(i = a[i]\)。那麼前面的可以直接數位dp/爆搜,後面的部分是經典問題,可以用逆康託展開計算。

#include<bits/stdc++.h> 
#define Pair pair<int, int>
#define MP(x, y) make_pair(x, y)
#define fi first
#define se second
#define int long long 
#define LL long long 
#define Fin(x) {freopen(#x".in","r",stdin);}
#define Fout(x) {freopen(#x".out","w",stdout);}
using namespace std;
const int MAXN = 1e6 + 1, mod = 1e9 + 7, INF = 1e9 + 10;
const double eps = 1e-9;
template <typename A, typename B> inline bool chmin(A &a, B b){if(a > b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline bool chmax(A &a, B b){if(a < b) {a = b; return 1;} return 0;}
template <typename A, typename B> inline LL add(A x, B y) {if(x + y < 0) return x + y + mod; return x + y >= mod ? x + y - mod : x + y;}
template <typename A, typename B> inline void add2(A &x, B y) {if(x + y < 0) x = x + y + mod; else x = (x + y >= mod ? x + y - mod : x + y);}
template <typename A, typename B> inline LL mul(A x, B y) {return 1ll * x * y % mod;}
template <typename A, typename B> inline void mul2(A &x, B y) {x = (1ll * x * y % mod + mod) % mod;}
template <typename A> inline void debug(A a){cout << a << '\n';}
template <typename A> inline LL sqr(A x){return 1ll * x * x;}
inline int read() {
    char c = getchar(); int x = 0, f = 1;
    while(c < '0' || c > '9') {if(c == '-') f = -1; c = getchar();}
    while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = getchar();
    return x * f;
}
int N, K, fac[MAXN];
vector<int> res;
int find(int x) {
    sort(res.begin(), res.end());
    int t = res[x];
    res.erase(res.begin() + x);
    return t;
}
bool check(int x) {
    while(x) {
        if((x % 10) != 4 && (x % 10) != 7) return 0;
        x /= 10;
    }
    return 1;
}
int ans;
void dfs(int x, int Lim) {//計算1 - lim中只包含4 7的數量 
    if(x > Lim) return ;
    if(x != 0) ans++;
    dfs(x * 10 + 4, Lim);
    dfs(x * 10 + 7, Lim);
}
signed main() {
    N = read(); K = read() - 1;
    int T = -1; fac[0] = 1;
    for(int i = 1; i <= N;i++) {
        fac[i] = i * fac[i - 1];
        res.push_back(N - i + 1);
        if(fac[i] > K) {T = i; break;}
    }
    if(T == -1) {puts("-1"); return 0;}
    dfs(0, N - T);
    for(int i = T; i >= 1; i--) {
        int t = find(K / fac[i - 1]), pos = N - i + 1;
        if(check(pos) && check(t)) ans++;
        K = K % fac[i - 1];
    }
    cout << ans;
    return 0;
}
/*

*/