-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaintabad.cpp
47 lines (42 loc) · 962 Bytes
/
paintabad.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
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100010;
int n;
int a[MAXN];
int pos[MAXN], nxt[MAXN];
void solve() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i)
scanf("%d", &a[i]);
for (int i = 0; i <= n; ++i)
pos[i] = n + 1;
for (int i = n; i >= 0; --i) {
nxt[i] = pos[a[i]];
pos[a[i]] = i;
}
int x = 0, y = 0; // the last elements of the two subarrays
int res = 0;
for (int z = 1; z <= n; ++z) {
// Greedy Strategy I
if (a[x] == a[z]) {
res += a[y] != a[z];
y = z;
} else if (a[y] == a[z]) {
res += a[x] != a[z];
x = z;
}
// Greedy Strategy II
else if (nxt[x] < nxt[y]) {
res += a[x] != a[z];
x = z;
} else {
res += a[y] != a[z];
y = z;
}
}
printf("%d\n", res);
}
int main() {
solve();
return 0;
}