-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathSortRankRepeat.java
100 lines (73 loc) · 2.04 KB
/
SortRankRepeat.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package Math;
import java.util.Arrays;
/**
* Author - archit.s
* Date - 30/09/18
* Time - 12:25 PM
*/
public class SortRankRepeat {
private static final int MOD = 1000003;
long fact(long A){
if(A <= 1){
return 1;
}
return A*fact(A-1) % MOD;
}
long modInv(long A, long y){
long res = 1;
while(y>0){
if((y & 1) == 1){
res = (res*A) % MOD;
}
A = (A*A) % MOD;
y >>= 1;
}
return res;
}
int smallerRight(String A, int low, int high){
char c = A.charAt(low);
int count = 0;
for(int i=low+1;i<=high;i++){
if(c > A.charAt(i)){
count++;
}
}
return count;
}
public int findRank(String A) {
int len = A.length();
long[] facts = new long[len+1];
long[] invFacts = new long[len+1];
facts[0] = invFacts[0] = 1;
for(int i=1;i<=len;i++){
facts[i] = (facts[i-1]*i) % MOD;
invFacts[i] = modInv(facts[i], MOD-2);
}
long rank = 0;
for(int i=0;i<len;i++){
int smaller = smallerRight(A, i, len-1);
int[] dupl = new int[52];
Arrays.fill(dupl, 0);
//count duplicates from that position to right
for(int j=i;j<len;j++){
if(A.charAt(j) >= 'A' && A.charAt(j) <= 'Z'){
dupl[A.charAt(j) - 'A']++;
}
else{
dupl[A.charAt(j) - 'a' + 26]++;
}
}
long temp = smaller*fact(len-i-1);
for(int j=0;j<52;j++){
if(dupl[j] > 0){
temp = (temp * invFacts[dupl[j]]) % MOD;
}
}
rank = (rank + temp) % MOD;
}
return new Long((rank+1) % MOD).intValue();
}
public static void main(String[] args) {
System.out.println(new SortRankRepeat().findRank("baa"));
}
}