USACO Sorting a Three-Valued Sequence

Code

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
/*
ID: wcr19961
PROG: sort3
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const int maxn = 1010;
int a[maxn], p[5];

int main() {
freopen("sort3.in", "r", stdin);
freopen("sort3.out", "w", stdout);
int n, ans = 0;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
scanf("%d", &a[i]);
++p[a[i]];
}
p[2] += p[1];
for (int i = 0; i < p[2]; ++i) {
if (i < p[1]) {
if (a[i] == 3) {
for (int j = n - 1; j >= p[1]; --j) {
if (a[j] == 1) {
swap(a[i], a[j]);
break;
}
}
++ans;
} else if (a[i] == 2) {
for (int j = p[1]; j < n; ++j) {
if (a[j] == 1) {
swap(a[i], a[j]);
break;
}
}
++ans;
}
} else {
if (a[i] == 3) {
++ans;
}
}
}
printf("%d\n", ans);
return 0;
}