-
Notifications
You must be signed in to change notification settings - Fork 103
/
birthday.cpp
69 lines (69 loc) · 1.81 KB
/
birthday.cpp
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
// 2024-09-03
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
using namespace std;
int main() {
int n; scanf("%d", &n);
if (n == 1) {
puts("0\n");
return 0;
}
vector<int> indexof(n);
for (int i = 0; i < n; i++) {
int x; scanf("%d", &x); --x;
indexof[x] = i;
}
unsigned cur = 0;
int step = 0;
vector<int> dstep(n);
for (int i = 0; i < n; i++) {
const int vec = (indexof[i] - i + n) % n;
cur += min(vec, n - vec);
if (n % 2 == 0) {
if (vec > n/2) {
step += 1;
dstep[vec - n/2] -= 2;
dstep[vec] += 2;
} else if (vec == n/2) {
step -= 1;
dstep[n/2] += 2;
} else if (vec > 0) {
step -= 1;
dstep[vec] += 2;
dstep[vec + n/2] -= 2;
} else {
step += 1;
dstep[n/2] -= 2;
}
} else {
if (vec > (n + 1)/2) {
step += 1;
dstep[vec - (n + 1)/2] -= 1;
dstep[vec - (n + 1)/2 + 1] -= 1;
dstep[vec] += 2;
} else if (vec == (n + 1) / 2) {
dstep[1] -= 1;
dstep[vec] += 2;
} else if (vec > 0) {
step -= 1;
dstep[vec] += 2;
dstep[vec + (n - 1)/2] -= 1;
dstep[vec + (n + 1)/2] -= 1;
} else {
step += 1;
dstep[(n - 1)/2] -= 1;
dstep[(n + 1)/2] -= 1;
}
}
}
unsigned best = cur;
int j = 0;
for (int i = 1; i < n; i++) {
cur += step;
best = min(best, cur);
step += dstep[i];
}
printf("%u\n", best);
}