UVA10063 Knuth‘s Permutation排列组合
Posted 海岛Blog
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA10063 Knuth‘s Permutation排列组合相关的知识,希望对你有一定的参考价值。
There are some permutation generation techniques in Knuth’s book “The Art of Computer Programming - Volume 1”. One of the processes is as follows:
For each permutation A1A2 . . . An−1 form n others by inserting a character n in all possible places obtaining
n
A
1
A
2...
A
n
−
1
,
A
1
n
A
2...
A
n
−
1
,
.
.
.
,
A
1
A
2...
n
A
n
−
1
,
A
1
A
2...
A
n
−
1
n
nA1A2 . . . An−1, A1nA2 . . . An−1, . . . , A1A2 . . . nAn−1, A1A2 . . . An−1n
nA1A2...An−1,A1nA2...An−1,...,A1A2...nAn−1,A1A2...An−1n
For example, from the permutation 231 inserting 4 in all possible places we get 4231 2431 2341 2314
Following this rule you have to generate all the permutation for a given set of characters. All the given characters will be different and there number will be less than 10 and they all will be alpha numerals. This process is recursive and you will have to start recursive call with the first character and keep inserting the other characters in order. The sample input and output will make this clear. Your output should exactly mach the sample output for the sample input.
Input
The input contains several lines of input. Each line will be a sequence of characters. There will be less
than ten alphanumerals in each line. The input will be terminated by “End of File”.
Output
For each line of input generate the permutation of those characters. The input ordering is very important for the output. That is the permutation sequence for ‘abc’ and ‘bca’ will not be the same.
Separate each set of permutation output with a blank line.
Sample Input
abc
bca
dcba
Sample Output
cba
bca
bac
cab
acb
abc
acb
cab
cba
abc
bac
bca
abcd
bacd
bcad
bcda
acbd
cabd
cbad
cbda
acdb
cadb
cdab
cdba
abdc
badc
bdac
bdca
adbc
dabc
dbac
dbca
adcb
dacb
dcab
dcba
问题链接:UVA10063 Knuth’s Permutation
问题简述:克努斯置换,生成排列组合的方法。
问题分析:排列组合问题,不解释。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA10063 Knuth's Permutation */
#include <bits/stdc++.h>
using namespace std;
const int N = 10;
char s[N + 1], ans[N + 1], len;
void dfs(int k)
{
if(k == len) {
ans[k] = '\\0';
puts(ans);
} else {
for(int i = k; i >= 1; i--)
ans[i] = ans[i - 1];
for(int i = 0; i <= k; i++) {
ans[i] = s[k];
dfs(k + 1);
ans[i] = ans[i + 1];
}
}
}
int main()
{
int flag = 1;
while(gets(s)) {
if(flag == 0) puts("");
flag = 0;
len = strlen(s);
dfs(0);
}
return 0;
}
以上是关于UVA10063 Knuth‘s Permutation排列组合的主要内容,如果未能解决你的问题,请参考以下文章
ZOJ 3957 Knuth-Morris-Pratt Algorithm
使用通配符生成 Knuth–Morris–Pratt 前缀表