[Aizu] ITP2_8_C: Map: Range Search

前言

ITP系列的题目, 只是为了了解基础的用法的, 所以为了提高效率, 不再记录完整的内容, 只侧重于本题中所使用到的一些知识

题目

传送门: ITP2_8_C: Map: Range Search

求解

用法

STL中map是通过红黑树实现的(不明觉厉).
详细请参阅文章C++中的hash_map和map的区别 - 追逐更好的自己

map的常用方法(只涉及到本题的部分)

方法名 描述 示例
insert((key, val)) 向map中插入元素(key, val) my_map.insert(make_pair(key, val));
erase(key) 删除含有key的元素 my_map.erase(key);
find(key) 搜索与key一致的元素, 并返回指向该元素的迭代器, 如果不存在, 则返回指向末尾的迭代器end() map<string, int>::iterator it = my_map.find(key);
lower_bound(key) 返回指向第一个不小于key的元素的迭代器 it1 = my_map.lower_bound(key);
upper_bound(key) 返回指向第一个大于key的元素的迭代器 it2 = my_map.upper_bound(key);
count(key) 返回与key键匹配的元素数 if (my_map.count(key))

编码

自己尝试使用STL的代码

#include <bits/stdc++.h>
using namespace std;

int main(void) {
	ios::sync_with_stdio(false);
	cin.tie(0);

	int q, com, x;
	string key, L, R;
	map<string, int> my_map;
	map<string, int>::iterator it1, it2, it;

	cin >> q;
	while (q--) {
		cin >> com >> key;
		switch (com) {
			case 0:
				cin >> x;
				if (my_map.end() != my_map.find(key)) {
					my_map.erase(key);
				}
				my_map.insert(make_pair(key, x));
				break;
			case 1:
				it = my_map.find(key);
				if (it != my_map.end()) {
					cout << it->second << endl;
				} else {
					cout << 0 << endl;
				}
				break;
			case 2:
				my_map.erase(key);
				break;
			case 3:
				L = key;
				cin >> R;
				it1 = my_map.lower_bound(L);
				it2 = my_map.upper_bound(R);
				for (it = it1; it != it2; it++) {
					cout << it->first << " " << it->second << endl;
				}
				break;
		}
	}
}

别人使用STL的代码

传送门: #3431194 Solution for ITP2_8_C by shioree

#include <bits/stdc++.h>
using namespace std;
 
int main() {
  int num_query; cin >> num_query;
  map<string, int> dic;
   
  while (num_query--) {
    int command; scanf("%d", &command);
    char key[20]; scanf("%s", key);
     
    switch (command) {
      case 0:
        int value; scanf("%d", &value);
        if (dic.count(key)) dic.at(key) = value;
        else dic.insert(make_pair(key, value));
        break;
         
      case 1:
        if (dic.count(key)) printf("%d\n", dic.at(key));
        else printf("%d\n", 0);
        break;
         
      case 2:
        dic.erase(key);
        break;
         
      case 3:
        char key2[20]; scanf("%s", key2);
        map<string, int>::iterator it = dic.lower_bound(key);
        map<string, int>::iterator last = dic.upper_bound(key2);
        while(it != last) {
          printf("%s %d\n", ((*it).first).c_str(), (*it).second);
          it++;
        }
        break;
    }
  }
}

记录

应该尝试使用count()方法去快速判断有无, 而不是使用find(), 它之后还需要一次与end()的比较, 而count()的返回值可以直接作为判断的条件

posted @ 2019-06-11 05:58  by-sknight  阅读(232)  评论(0)    收藏  举报