题解 |map容器解决绝大多数的查找问题
魔咒词典
https://www.nowcoder.com/practice/c6ca566fa3984fae916e6d7beae8ea7f
//map容器解决绝大多数的查找问题,而且由于底层是红黑树,时间复杂度较低 #include "stdio.h" #include "string" #include "map" using namespace std; int main(){ char buf[102]; map<string,string> myMap1;//魔咒为键 map<string,string> myMap2;//解释为键 while (true){ fgets(buf,102,stdin); string str = buf;str.pop_back(); if (str == "@END@") break; else{ int pos = str.find(']'); string magic = str.substr(1,pos-1); string expression = str.substr(pos+2); myMap1[magic] = expression; myMap2[expression] = magic; } } int m; scanf("%d",&m); getchar(); char buf2[102]; for (int i = 0; i < m; ++i) { fgets(buf2,82,stdin); string HaLi = buf2;HaLi.pop_back(); if (HaLi[0] == '['){ //问的是咒语的含义,查map1 HaLi = HaLi.substr(1,HaLi.size()-2); map<string,string>::iterator it = myMap1.find(HaLi); if (it != myMap1.end()) printf("%s\n",it->second.c_str()); else printf("what?\n"); } else{ //问的是功能对应的咒语,查map2 map<string,string>::iterator it = myMap2.find(HaLi); if (it != myMap2.end()) printf("%s\n",it->second.c_str()); else printf("what?\n"); } } }