#include <iostream>
#include <vector>
#include <unordered_set>
#include <algorithm>
#include <map>
#include <list>
using namespace std;
// Hàm tính chi phí dựa trên Quy tắc: Miss = |D|+1, Hit = |D| (hoặc N)
long long calculate_cost(bool is_miss, int N, int current_size) {
if (is_miss) {
// Miss: 1 (chuyển lên) + |D| (dịch chuyển)
return (long long)current_size + 1;
} else {
// Hit: |D| (số dụng cụ bị dịch chuyển)
return (long long)current_size;
}
}
void solve() {
int N, k;
if (!(cin >> N >> k)) return;
vector<int> requests(k);
for (int i = 0; i < k; ++i) {
cin >> requests[i];
}
// 1. Tiền xử lý lần sử dụng tiếp theo (Optimal strategy)
map<int, vector<int>> next_use_pos;
for (int i = 0; i < k; ++i) {
next_use_pos[requests[i]].push_back(i);
}
map<int, int> next_occurrence_ptr;
for(auto const& [tool_id, positions] : next_use_pos) {
next_occurrence_ptr[tool_id] = 0;
}
// List và Set cho Cache
list<int> cache_list;
unordered_set<int> cache_set;
long long total_cost = 0;
for (int i = 0; i < k; ++i) {
int current_tool = requests[i];
bool is_miss = (cache_set.find(current_tool) == cache_set.end());
int current_size = cache_set.size();
// 1. Tính chi phí
total_cost += calculate_cost(is_miss, N, current_size);
// 2. Cập nhật Cache
if (!is_miss) {
// Hit: Dụng cụ vừa dùng được đẩy lên đầu (vị trí 1)
cache_list.remove(current_tool);
cache_list.push_front(current_tool);
} else {
// Miss
// 2a. Cache chưa đầy
if (current_size < N) {
// Thêm mới
}
// 2b. Cache đã đầy -> Thay thế theo quy tắc Optimal
else {
int tool_to_remove = -1;
int max_next_use_index = -1;
// Chiến lược Optimal (Belady): Tìm dụng cụ được dùng lại xa nhất
for (int tool : cache_set) {
int current_ptr = next_occurrence_ptr[tool];
int next_use_index = -1;
if (current_ptr < next_use_pos[tool].size()) {
next_use_index = next_use_pos[tool][current_ptr];
}
if (next_use_index == -1) {
tool_to_remove = tool;
break;
}
if (next_use_index > max_next_use_index) {
max_next_use_index = next_use_index;
tool_to_remove = tool;
}
}
// Thực hiện thay thế
if (tool_to_remove != -1) {
cache_set.erase(tool_to_remove);
cache_list.remove(tool_to_remove);
}
}
// Thêm dụng cụ mới (luôn ở vị trí 1/đầu list)
cache_set.insert(current_tool);
cache_list.push_front(current_tool);
}
// Cập nhật con trỏ lần xuất hiện tiếp theo
next_occurrence_ptr[current_tool]++;
}
cout << total_cost << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
solve();
return 0;
}