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

CSU1563 组合数学

时间:2015-04-20 01:52:44      阅读:152      评论:0      收藏:0      [点我收藏+]

标签:组合数学

C - Lexicography
Time Limit:1000MS     Memory Limit:131072KB     64bit IO Format:%lld & %llu

Description

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个排列。如果确定第一个字符为x,计算出首字符小于x的排列种数tot,则原问题转化成求首字符为x的第k-tot个排列,一直这么处理到最后一个字符。



#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
typedef long long ll;
#define rep(i,a,b) for(int i = (a);i < (b); ++i)
ll f[20];
int main(int argc, char const *argv[])
{
    f[0] = 1;
    rep(i,1,20) f[i] = f[i-1]*i;
    char s[20];
    long long m;
    while(~scanf("%s%lld", s, &m)) {
        if(s[0]=='#'&&!m)return 0;
        int sz = strlen(s);
        int cnt[30];
        memset(cnt,0,sizeof cnt);
        rep(i,0,sz) cnt[s[i]-'A']++;
        rep(i,0,sz) {
            ll tot = 0;
            rep(j,0,26)if(cnt[j]){
                ll t = f[sz-i-1];/*以i+'A'开头的多重排列个数*/
                rep(k,0,26) {   
                    if(k==j) t /= f[cnt[k]-1];
                    else t /= f[cnt[k]];
                }
                if(tot+t>=m) {
                    s[i] = j + 'A';
                    m -= tot;
                    cnt[j]--;
                    break;
                }else tot += t;/*首字符小于等于j+'A'的多重排列个数*/
            }
        }
        puts(s);
    }
    return 0;
}


CSU1563 组合数学

标签:组合数学

原文地址:http://blog.csdn.net/acvcla/article/details/45138031

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