现在有"abcdefghijkl”12个字符,将其所有的排列中按字典序排列,给出任意一种排列,说出这个排列在所有的排列中是第几小的?

本文介绍了一种计算字符排列在所有可能排列中序位的方法。通过递归算法确定排列的位置,利用字典序来判断排列的先后顺序。该算法适用于求解给定字符串在所有可能排列中的具体位置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在有"abcdefghijkl”12个字符,将其所有的排列中按字典序排列,给出任意一种排列,说出这个排列在所有的排列中是第几小的?


输入

第一行有一个整数n(0<n<=10000);

随后有n行,每行是一个排列;

样例输入

3

abcdefghijkl

hgebkflacdji

gfkedhjblcia

输出

输出一个整数m,占一行,m表示排列是第几位;

样例输出

1

302715242

260726926

public class Main {

	public static long postion (int n){
	   if(n==1){
			return 1;
		}
		return n*postion(n-1);
	}
	public static long index(char[] p,char c,int inde){
       int size=1;
		for (int i = 0; i < inde; i++) {
	    if(c-p[i]>0){
	    	size++;
	    }	
	   }
		
		return (c-96)-size;
   }
	
	public static long getSize(char[] p,int index,long size){
		 char c=p[index];
		 if(index==p.length-1){
			return 1;
		 }
		 long num=index(p, c, index)*postion(12-index-1);
	     return  num+getSize(p, ++index, num);

	}
	public static void main(String[] args) {
	  Scanner sc=new Scanner(System.in);
	  int n=sc.nextInt();
	  sc.nextLine();
	  for (int i = 0; i < n; i++) {
		String str=sc.nextLine();
		char [] cc=str.toCharArray();
		System.out.println(getSize(cc, 0, 0));
	  }

	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值