1. 题目来源
2. 题目解析
水题,unordered_map<>
基本使用。
坑点:
unordered_map
即哈希表,不论对其赋值与否都会在哈希表中插入这个值,即res += hash[t]
,若t
查找不到则res += 0
也不影响正确结果,但是这个无用的t
会被插入到哈希表中。
代码:
// https://www.luogu.com.cn/problem/P5266
#include <iostream>
#include <cstdio>
#include <string>
#include <unordered_map>
using namespace std;
int n;
unordered_map<string, int> h;
int main() {
scanf("%d", &n);
for (int i = 0; i < n; i ++ ) {
int op;
string s;
int sum;
scanf("%d", &op);
if (op == 1) {
cin >> s >> sum;
h[s] = sum, printf("OK\n");
}
else if (op == 2) {
cin >> s;
if (h.count(s)) printf("%d\n", h[s]);
else printf("Not found\n");
}
else if (op == 3) {
cin >> s;
if (h.count(s)) h.erase(s), printf("Deleted successfully\n");
else printf("Not found\n");
}
else printf("%d\n", h.size());
}
}
测试代码:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
unordered_map<int, int> h;
h[1] = 1;
h[2] = 2;
cout << h.size() << endl;
if (h.find(3) != h.end()) cout << 1 << endl;
int res = 0;
res += h[3];
if (h.count(3)) cout << 2 << endl;
cout << h.size() << ' ' << res << endl;
return 0;
}
/*
2
2
3 0
*/