计算当前序列的字典序序号(洛谷P2524题题解,Java语言描述)

题目要求

P2524题目链接

在这里插入图片描述

分析

这题就用康托展开吧:
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));
    }
    
}
发布了479 篇原创文章 · 获赞 972 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/weixin_43896318/article/details/104237069