LightOJ - 1060 nth Permutation(计数)

题目大意:给你一个字符串,问这个字符串的字典序排第n的字符串是什么

解题思路:计数问题,依此判断每一位即可

#include <cstdio>
#include <cstring>
using namespace std;
typedef long long LL;
const int N = 30;

LL A[N];
int cnt[N];
char str[N], ans[N];
LL k;
int cas = 1, len;

void start() {
    A[0] = A[1] = 1;
    for (int i = 2; i < 21; i++)
        A[i] = A[i - 1] * i;
}

LL Calculate() {
    LL t1 = 0, t2 = 1;
    for (int i = 0; i < 26; i++) {
        t1 += cnt[i];
        t2 *= A[cnt[i]];
    }
    return A[t1] / t2;
}

bool dfs(int pos, int cur, LL left) {
    if (pos >= len) return true;

    if (cnt[cur] == 0) return dfs(pos, cur + 1, left);
    cnt[cur]--;
    LL t = Calculate();
    if (t >= left) {
        ans[pos] = 'a' + cur;
        return dfs(pos + 1, 0, left);
    }
    else {
        cnt[cur]++;
        return dfs(pos, cur + 1, left - t);
    }
}

void solve() {
    scanf("%s%lld", str, &k);
    len = strlen(str);
    memset(cnt, 0, sizeof(cnt));
    for (int i = 0; i < len; i++)
        cnt[str[i] - 'a']++;
    if (Calculate() < k) printf("Case %d: Impossible\n", cas++);
    else  {
        ans[len] = '\0';
        dfs(0, 0, k);
        printf("Case %d: %s\n", cas++, ans);
    }
}

int main() {
    start();
    int test;
    scanf("%d", &test);
    while (test--) solve();
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值