给出一个可能包含重复数字的排列,求这些数字的所有排列按字典序排序后该排列在其中的编号。编号从1开始。
样例
样例
给出排列[1, 4, 2, 2],其编号为3。
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Scanner;
/**
* 给出一个可能包含重复数字的排列,求这些数字的所有排列按字典序排序后该排列在其中的编号。编号从1开始。
样例
给出排列[1, 4, 2, 2],其编号为3。
*
* @author Dell
*
*/
public class Test198 {
public static int find(int[] b ,int target)
{ int index=-1;
for(int i=0;i<b.length;i++)
{
if(b[i]==target)
{
index=i;
break;
}
}
return index;
}
public static long f(int n)
{
if(n==0||n==1)
return 1;
else
return n*f(n-1);
}
public static long permutationIndex(int[] a)
{ if(a.length==0)
return 0;
if(a.length==1)
return 1;
long sum=0;
for(int i=0;i<a.length-1;i++)
{
int[] temp=Arrays.copyOfRange(a, i, a.length);
Arrays.sort(temp);
int x=find(temp,a[i]);
HashMap<Integer,Integer> map=cishu(a,i);
long dup=1;
for(Entry<Integer,Integer> e : map.entrySet())
{
dup=dup*f(e.getValue());
}
sum=sum+(x*f(a.length-1-i))/dup;
}
return sum+1;
}
public static HashMap<Integer,Integer> cishu(int[] a, int i)
{
HashMap<Integer,Integer> map=new HashMap<>();
for(int j=i;j<a.length;j++)
{
if(!map.containsKey(a[j]))
{
map.put(a[j], 1);
}
else
{
map.put(a[j], map.get(a[j])+1);
}
}
return map;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int[n];
for(int i=0;i<a.length;i++)
{
a[i]=sc.nextInt();
}
System.out.println(permutationIndex(a));
}
}