Codeforces Round #699 (Div. 2) E. Sorting Books
題目連結
One day you wanted to read something, so you went to your bookshelf to grab some book. But when you saw how messy the bookshelf was you decided to clean it up first.
There are n n n books standing in a row on the shelf, the i i i-th book has color a i a_i ai.
You’d like to rearrange the books to make the shelf look beautiful. The shelf is considered beautiful
In one operation you can take one book from any position on the shelf and move it to the right end of the shelf.
What is the minimum number of operations you need to make the shelf beautiful?
Input
The first line contains one integer
n
n
n (
1
≤
n
≤
5
⋅
1
0
5
1 \le n \le 5 \cdot 10^5
The second line contains n n n integers a 1 , a 2 , … , a n a_1, a_2, \dots, a_n a1,a2,…,an ( 1 ≤ a i ≤ n 1 \le a_i \le n 1≤ai≤n) — the book colors.
Output
Output the minimum number of operations to make the shelf beautiful.
Examples
input
5
1 2 2 1 3
output
2
input
5
1 2 2 1 1
output
1
Note
In the first example, we have the bookshelf [ 1 , 2 , 2 , 1 , 3 ] [1, 2, 2, 1, 3] [1,2,2,1,3] and can, for example:
- take a book on position 4 4 4 and move to the right end: we’ll get [ 1 , 2 , 2 , 3 , 1 ] [1, 2, 2, 3, 1] [1,2,2,3,1];
- take a book on position 1 1 1 and move to the right end: we’ll get [ 2 , 2 , 3 , 1 , 1 ] [2, 2, 3, 1, 1] [2,2,3,1,1].
In the second example, we can move the first book to the end of the bookshelf and get [ 2 , 2 , 1 , 1 , 1 ] [2,2,1,1,1] [2,2,1,1,1].
f
[
i
]
f[i]
f[i] 表示序列前
i
i
i 個元素如果刪掉一些元素使得剩餘元素相同的相鄰且剩餘每種元素沒有被刪過,則最多剩餘的元素數量。
m
x
[
i
]
mx[i]
mx[i] 表示序列
i
∼
n
i\sim n
i∼n 的元素中出現次數最多的元素的數量。
最優策略一定是序列前一部分在移走一部分元素後剩餘部分滿足條件,而後一部分出現次數最多與前一部分移過來的該種元素組成連續段,剩餘部分也移到最後重組。
dp 完
f
f
f 後列舉前後部分的分界線即可得到答案。時間複雜度為
O
(
n
)
O(n)
O(n) 。
#include<bits/stdc++.h>
using namespace std;
const int N = 5e5 + 10;
int st[N], ed[N], mx[N], num[N];
int n, a[N], f[N];
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; ++i)scanf("%d", &a[i]);
for (int i = n; i >= 1; --i) {
if (!ed[a[i]])ed[a[i]] = i;
mx[i] = max(mx[i - 1], ++num[a[i]]);
st[a[i]] = i;
}
for (int i = 1; i <= n; ++i) {
f[i] = f[i - 1];
if (i == ed[a[i]])f[i] = max(f[i], f[st[a[i]] - 1] + num[a[i]]);
}
int d = 0;
for (int i = 0; i <= n; ++i)d = max(d, f[i] + mx[i + 1]);
printf("%d\n", n - d);
return 0;
}