第十章 哈希表和unordered_set之实验篇

📅 发布时间:2026/8/25 14:31:23
第十章 哈希表和unordered_set之实验篇 1P5266 【深基17.例6】学籍管理1,链接https://www.luogu.com.cn/problem/P52662题目3解析用unordered_map即可4代码#includeiostream #includeunordered_map using namespace std; unordered_mapstring ,int mp; int main(){ int q; cin q; while(q--){ int op; cin op; if(op 1){ string name; cin name; int x; cin x; mp[name] x; cout OKendl; } else if(op 2){ string name; cin name; if(mp.count(name)) cout mp[name] endl; else cout Not found endl; } else if(op 3){ string name; cin name; if(mp.count(name)){ mp.erase(name); cout Deleted successfully endl; } else cout Not found endl; } else{ cout mp.size() endl; } } return 0; }2P4305 [JLOI2011] 不重复数字1,链接https://www.luogu.com.cn/problem/P43052题目3解析unordered_set4代码#includeiostream #includeunordered_set using namespace std; int main(){ int t; cin t; while(t--){ unordered_setint mp; int n; cin n; while(n--){ int x; cin x; if(!mp.count(x)){ cout x ; mp.insert(x); } } cout endl; } return 0; }3P3879 [TJOI2010] 阅读理解1,链接https://www.luogu.com.cn/problem/P38792题目3解析大家一定还记得在理论篇中我们学过unordered_mapstring,vectorint mp;但我们发现只需要知道一篇文章出现过没有不需要知道出现几次所以用unordered_mapstring,setint mp;//单词-出现文章编号集合4代码#include iostream #include set #include unordered_map using namespace std; unordered_mapstring, setint mp; // 标记单词在哪些文章中出现过 int main() { int n; cin n; for (int i 1; i n; i) { int l; cin l; while (l--) { string s; cin s; mp[s].insert(i); } } int m; cin m; while (m--) { string s; cin s; for (auto i : mp[s]) { cout i ; } cout endl; } return 0; }4P1102 A-B 数对1,链接https://www.luogu.com.cn/problem/P11022题目3解析1,转换思想因为枚举的是B所以要找对应的AA-B C-A BC2步骤1先统计数组中每个数出现的次数- ll,ll//数次数2枚举所有B找CB出现次数4代码#include iostream #include unordered_map using namespace std; typedef long long ll; const int N 2e5 10; ll n, c; ll a[N]; unordered_mapll, ll mp; // 数, 该数出现的次数 int main() { cin n c; for (int i 1; i n; i) { cin a[i]; mp[a[i]]; } ll ret 0; for (int i 1; i n; i) ret mp[c a[i]]; cout ret endl; return 0; }5P3405 [USACO16DEC] Cities and States S1,链接https://www.luogu.com.cn/problem/P34052题目3解析1题意理解ab,xy的对应关系中找多少xy,ab这样对应的城市-ab,xy- ab 直接变成字符串就好存储了2方法哈希表统计 拼接后对应关系次数4代码#include iostream #include unordered_map using namespace std; int main() { int n; cin n; unordered_mapstring, int mp; // 拼接后的对应关系, 次数 int ret 0; while (n--) { string a, b; cin a b; a a.substr(0, 2); if (a b) continue; ret mp[b a]; mp[a b]; } cout ret endl; return 0; }