3. 用C++的map来实现
看着用C实现起来,相对来说实现的各个功能都要自己写,这里看一下用C++的STL里面的map来实现上面的题目,非常简单(不得不说STL真的很好用,但是不如HashTable速度快,空间上也不如HashTable占用的小)
#include <iostream>
#include <map>
using namespace std;
int main() {
int n, q;
cin >> n >> q;
map<int,int> mp;
map<int,int>::iterator it;
int x, y, z;
for (int i=1; i<n; ++i) {
cin >> x >> y;
mp.insert(pair<int,int>(y,x));
}
int sum = 0;
for (int i=0; i<q; ++i) {
cin >> z;
it = mp.find(z);
if (it != mp.end()) {
it = mp.find(it->second);
if (it != mp.end())
sum += it->second;
}
}
cout << sum;
return 0;
}
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!
注:相关教程知识阅读请移步到C++教程频道。










