样例题:https://codeforces.com/contest/1234/problem/B2

主要是需要对每个数字 Ai 保存的位置进行记录,Ai 最大是1e9,会导致数组保存不了,于是想到map

map的功能:建立key - value的对应,key和value可以是任意类型

定义与初始化:

#include<map>
map<int, int> mp;
mp.clear();

map<string, int> mp;
mp.clear();

增加:

map<int, string> mp;
mp.insert(pair<int, string>(0, "student0"));
mp.insert(map<int, string>::value_type(1, "student1"));
mp[1]="student1";

第一种和第二种方式(即insert方式),涉及到集合的唯一性的概念。即当map中存在该值时,insert操作不成功。而用数组方式肯定会有修改。即mp中没有则新增,mp中有则更新。

删除:

iter = mp.find("1");
mp.earse(iter);

int ret = mp.erase("1");
//success => ret = 1
//fail => ret = 0

mp.earse(mp.begin(), mp.end());
mp.clear();

修改:

mp["123"] = 456;

查找:

iter = mp.find("123");
if (iter != mp.end())
    //find success
else
    //find fail

遍历:

map<string, int>::iterator iter;
map<string, int>::const_iterator iter;
map<string, int>::reverse_iterator iter;
map<string, int>::const_reverse_iterator iter;
map<int, int>::iterator iter;
iter = mp.begin();
while(iter != mp.end()){
    //do sth
    iter++;
}

边界判断与查找:

map::lower_bound(key);
//>=key

map::upper_bound(key);
//>key

其他函数:

mp.count()
mp.equal_range()
mp.max_size()
mp.rbegin()
mp.rend()
mp.size()
mp.swap()
mp.value_comp()

样例题代码:

    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
    #include <map>
    using namespace std;
     
    const int maxn = 2e5 + 1000;
    //int pos[maxn];
    map<int, int> pos;
    int ans[maxn];
    int n,k;
     
    int main(){
    	int len = 0, x, y, st, ed, length;
    	scanf("%d%d", &n, &k);
    	//memset(pos, -1, sizeof(pos));
    	pos.clear();
    	memset(ans, -1, sizeof(ans));
    	for(int i = 1; i <= n; i++){
    		scanf("%d", &x);
    		if (len < k){
    			st = 1;
    			ed = len;
    			if (pos[x] >= st && pos[x] <= ed) continue;
    			else{
    				len++;
    				ans[len] = x;
    				pos[x] = len;
    			}
    		}
    		else{
    			st = len - k + 1;
    			ed = len;
    			if (pos[x] >= st && pos[x] <= ed) continue;
    			else{
    				len++;
    				ans[len] = x;
    				pos[x] = len;
    			}
    		}
    	}
    	if (len < k) length = len;
    	else length = k;
    	//int length = min(len, k);
    	printf("%d\n", length);
    	//printf("%d\n", len);
    	for(int i = len; i >= len - length + 1; i--)
    		printf("%d%c", ans[i], i == len - length + 1 ? '\n':' ');
    	return 0;
    }