CSU 1563 Lexicography

本文介绍了一种算法,用于解决给定一个字符串和一个排名K后,如何找到该字符串的第K个字谜(即由原字符串字母重新排列形成的字符串)。通过递归地计算不同字符开头的所有可能排列的数量,并根据K值确定每个位置应放置的字符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

An anagram of a string is any string that can be formed using the same letters as the original. (We consider the original string an anagram of itself as well.) For example, the string ACM has the following 6 anagrams, as given in alphabetical order:

ACM
AMC
CAM
CMA
MAC
MCA
As another example, the string ICPC has the following 12 anagrams (in alphabetical order):

CCIP
CCPI
CICP
CIPC
CPCI
CPIC
ICCP
ICPC
IPCC
PCCI
PCIC
PICC
Given a string and a rank K, you are to determine the Kth such anagram according to alphabetical order.

Input

Each test case will be designated on a single line containing the original word followed by the desired rank K. Words will use uppercase letters (i.e., A through Z) and will have length at most 16. The value of K will be in the range from 1 to the number of distinct anagrams of the given word. A line of the form "# 0" designates the end of the input.

Output

For each test, display the Kth anagram of the original string.

Sample Input
ACM 5
ICPC 12
REGION 274
# 0
Sample Output
MAC
PICC
IGNORE
Hint

The value of K could be almost 245 in the largest tests, so you should use type long in Java, or type long long in C++ to store K.


简单的说就是找全排列的第k个是谁,可以枚举第一个放什么的方案数,小于说明就在里面,大于说明在后面里,减去之后再向后找,递归下去就行了,计算方案数的时候考虑排列组合的方式,由n!/A!/B!/C!....

分别表示不同的字母的个数。

#include<cstdio>  
#include<cstring>
#include<cstdio>
#include<algorithm>  
using namespace std;
const int N = 1e5 + 10;
char s[N], a[N];
int m;
long long n;

long long calc(int x) {
	sort(s + x, s + m);
	long long ans = 1;
	for (int i = x; i < m; i++) ans *= i - x + 1;
	for (int i = x + 1, j = 1; i < m; i++) {
		if (s[i] == s[i - 1]) j++; else j = 1;
		ans /= j;
	}
	return ans;
}

void dfs(int x, long long rk) {
	for (int i = x; i < m; i++) a[i] = s[i];
	sort(a + x, a + m);
	int sz = unique(a + x, a + m) - a;
	for (int i = x; i < sz; i++) {
		for (int j = x; j < m; j++) {
			if (s[j] == a[i]) {
				swap(s[j], s[x]); 
				break;
			}
		}
		long long temp = calc(x + 1);
		if (rk > temp) {
			rk -= temp;
		} else {
			dfs(x + 1, rk);
			return;
		}
	}
}

int main(){
	while (~scanf("%s%lld", s, &n) && n) {
		m = strlen(s);
		dfs(0, n);
		printf("%s\n", s);
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值