码迷,mamicode.com
首页 > 其他好文 > 详细

UVA - 12335 Lexicographic Order (第k大排列)

时间:2014-08-14 14:11:48      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   os   io   strong   

Description

bubuko.com,布布扣

A

Lexicographic Order

Input: Standard Input

Output: Standard Output

bubuko.com,布布扣

 

The alphabet of a certain alien language consists of n distinct symbols. The symbols are like the letters of English alphabet but their ordering is different. You want to know the original order of the symbols in that particular alphabet. You have a string consists of all the letters of that alphabet and you know that this is the k-th (1 based) lexicographic permutation of these symbols. You have to arrange these symbols in lexicographic order of that language.

 

Input

The first line of input will contain an integer T (T ≤ 5000) which denotes the number of test cases.

 

Each of the following T lines contains a string s and an integer k. The string will be of length n (1 ≤ n ≤ 20) and will consist of lowercase letters only. All the letters in the string will be distinct. The value of k will be in the range (1 ≤ k ≤ n!).

 

Output

For each line of input output the case number and a string which contains the letters in lexicographic order in that language.

 

Sample Input                              Output for Sample Input

3
bdac 11
abcd 5
hjbrl 120

Case 1: abcd
Case 2: acdb
Case 3: lrbjh

题意:求第n大的排列

思路:举个简单的例子:序列:1234,求第11个排列,假设我们确定了第一个,那么剩下3个的排列数是3!,因为12是大于6的,所以我们不能放1放到第一个,当我们放2的时候,这个数能有的排列会到12<=12,所以我们就能确定第一个是2了,依次类推

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
typedef long long ll;
using namespace std;
const int maxn = 30;

char str[maxn], ans[maxn];
int n, vis[maxn], ind[maxn]; 

ll cal(int x) {
	ll tmp = 1;
	for (int i = 2; i <= x; i++)
		tmp *= i;
	return tmp;
}

void dfs(int cur , ll dir) {
	if (cur == n)
		return;
	ll tmp = cal(n-cur-1);
	for (int i = 0; i < n; i++) {
		if (vis[i])
			continue;
		if (dir > tmp)
			dir -= tmp;
		else {
			vis[i] = 1;
			ind[cur] = i;
			dfs(cur+1, dir);
			return;
		}

	}
}

int main() {
	ll x;
	int t, cas = 1;
	scanf("%d", &t);
	while (t--) {
		scanf("%s%lld", str, &x);
		n = strlen(str);
		memset(vis, 0, sizeof(vis));
		dfs(0, x);
		printf("Case %d: ", cas++);
		for (int i = 0; i < n; i++)
			ans[ind[i]] = str[i];
		for (int i = 0; i < n; i++)
			printf("%c", ans[i]);
		printf("\n");
	}
	return 0;
}


UVA - 12335 Lexicographic Order (第k大排列),布布扣,bubuko.com

UVA - 12335 Lexicographic Order (第k大排列)

标签:des   style   blog   http   color   os   io   strong   

原文地址:http://blog.csdn.net/u011345136/article/details/38556467

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!