UVa 941: Permutations 排列?其实是阶乘

来源:互联网 发布:网络克隆和标准交换 编辑:程序博客网 时间:2024/05/21 18:31

原题链接:UVa 941-Permutations

题目大意:题目意思很简单,就是给定一个字符串,给出字符串中字符按字典序排序的第N个元素。

大致思路:使用<algorithm>中的next_permutation函数遍历所有情况,代码如下:

#include <cstdio>#include <cstring>#include <list>#include <algorithm>using namespace std;char str[25];int main() {int N, num, len;scanf("%d", &N);while(N--) {scanf("%s", str);scanf("%d", &num);len = strlen(str);sort(str, str+len);while(num--) {next_permutation(str,str+len);}printf("%s\n", str);}return 0;}
遍历所有情况的方式逻辑比较简单,但是当输入较大时则会出现超时,所以使用另一种方式:

#include <cstdio>#include <cstring>#include <list>#include <algorithm>using namespace std;char str[25];long long fac(int n) {if(n==0) return 1;else if(n==1) return 1;else return n*fac(n-1);}int main() {int N, len, rem;long long num, factor;scanf("%d", &N);while(N--) {scanf("%s", str);scanf("%lld", &num);num++;len = strlen(str);sort(str, str+len);list<char> mylist(str, str+len);list<char>::iterator it = mylist.begin();factor = fac(len-1);while(len!=0) {rem = num / factor;num = num % factor;if(num==0) num = factor;else rem++;for(int i=0; i<rem-1; i++) it++;putchar(*it);mylist.erase(it);len--;if(len) factor /= len;it = mylist.begin();}printf("\n");}return 0;}

0 0