Skip to content

Commit 453afe8

Browse files
committed
Solved problem Lazy Sorting HackerRank
1 parent 5cde89f commit 453afe8

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

Hackerrank/Lazy Sorting.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/*
2+
- Idea:
3+
- If the array if sorted then the expected value is 0.
4+
- Otherwise declare fr_i to be the frequency of the i_th element
5+
in the array, so we can sort the array in `all` = (fr_1! * fr_2! * ... * fr_n!)
6+
ways, then the probability to sort the array after shuffling is `all/N!`,
7+
finally the expected value if `1/(all/N!)` which is equal to `N!/all`.
8+
*/
9+
10+
#include <bits/stdc++.h>
11+
12+
using namespace std;
13+
14+
int n, a[18], b[18], fr[101];
15+
16+
long long fact(int x) {
17+
long long ret = 1;
18+
for(int i = 2; i <= x; ++i)
19+
ret *= i;
20+
return ret;
21+
}
22+
23+
int main() {
24+
scanf("%d", &n);
25+
for(int i = 0; i < n; ++i)
26+
scanf("%d", a + i), b[i] = a[i], ++fr[a[i]];
27+
28+
sort(b, b + n);
29+
30+
bool ok = true;
31+
for(int i = 0; i < n; ++i)
32+
if(a[i] != b[i])
33+
ok = false;
34+
35+
if(ok) {
36+
puts("0");
37+
return 0;
38+
}
39+
40+
long long all = fact(n);
41+
42+
for(int i = 0; i <= 100; ++i)
43+
all /= fact(fr[i]);
44+
45+
printf("%lld\n", all);
46+
47+
return 0;
48+
}

Hackerrank/README.md

+1
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
- [Jack goes to Rapture](https://www.hackerrank.com/challenges/jack-goes-to-rapture)
3131
- [Journey to the Moon](https://www.hackerrank.com/challenges/journey-to-the-moon)
3232
- [Jumping on the Clouds](https://www.hackerrank.com/challenges/jumping-on-the-clouds)
33+
- [Lazy Sorting](https://www.hackerrank.com/challenges/lazy-sorting)
3334
- [Little Ashish's Huge Donation](https://www.hackerrank.com/challenges/little-chammys-huge-donation)
3435
- [Maximizing XOR](https://www.hackerrank.com/challenges/maximizing-xor)
3536
- [Maximum Draws](https://www.hackerrank.com/challenges/maximum-draws)

0 commit comments

Comments
 (0)