STL之C++中map

樣例題: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;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章