题目要求
分析
这题就用康托展开吧:
result = a[n] * [(n-1)!] + a[n-1] * [(n-2)!] + … + a[1] * [0!]
实现代码:
private static int cantor(int num, char[] chars) {
int result = 1;
for(int i = 0; i < num; i++) {
int temp = 0;
for(int j = i+1; j < num; j++) {
if(chars[i] > chars[j]) {
temp++;
}
}
result += temp * factorial[num-i-1];
}
return result;
}
先把阶乘的数据打好就完事……
当然,C++的STL还有这么个函数:next_permutation(),可以生成下一序列,也可利用这个函数来做。
AC代码(Java语言描述)
import java.util.Scanner;
public class Main {
private static int[] factorial = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
private static int cantor(int num, char[] chars) {
int result = 1;
for(int i = 0; i < num; i++) {
int temp = 0;
for(int j = i+1; j < num; j++) {
if(chars[i] > chars[j]) {
temp++;
}
}
result += temp * factorial[num-i-1];
}
return result;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int num = scanner.nextInt();
char[] chars = scanner.next().toCharArray();
scanner.close();
System.out.println(cantor(num, chars));
}
}