STL应用 map HDU 3527

HDU 3527 https://vjudge.net/problem/HDU-3527
继续上一题 这题还可以使用map解答

map 是一个将独一无二的键值与数值对应的数据结构,方便查找。
c++ stl中的map实现是树结构,所以存储的键值是有次序的排列。
还有另一种键值与数值对应的数据结构 unordered_map,使用的是哈希表,查找效率更高,但是存储的键值是无序排列。

常用的类函数如下:
operator[]
begin() end()
empty()
clear()
insert()
erase()
swap()
count()
find()

我们再来看看题目

题目的大意就是有三份名单,一份是所有旅客,一份是A间谍名单,一份是B间谍名单。
要求 我们找出现在A名单上但是未出现在B名单上的的旅客间谍(也就是同时还出现在第一份名单上)。

输入格式
第一行三个数字 空格隔开 表示三份名单的长度 A B C
第二行有A个名字 空格隔开
第三行有B个名字 空格隔开
第四行有C个名字 空格隔开

输出格式
输出一样 输出答案名字 空格隔开

Sample Input
8 4 3
Zhao Qian Sun Li Zhou Wu Zheng Wang
Zhao Qian Sun Li
Zhao Zhou Zheng
2 2 2
Zhao Qian
Zhao Qian
Zhao Qian

Sample Output
Qian Sun Li
No enemy spy

使用map解答
我们使用3个map记录旅客 A间谍 B间谍名单
然后将A间谍名单中所有名字 依次检查是否存在在旅客名单但是不在B间谍名单中。
符合条件就放入答案中 然后输出。
由于结构设计的优势,map在查找上胜出vector一筹,速度会更快。

代码如下


#include <iostream>
#include <map>
#include <vector>
#include <string>

 

using namespace std;


int a, b, c;

int main() {
	while (cin >> a >> b >> c) {
		map<string, int> vis;
		vector<string> A;//因为答案输出要求按照名单次序 所以这里不能使用map,会改变次序
		map<string, int> B;
		string s;
		for (int i = 0; i < a; i++) {
			cin >> s; vis[s]++;
		}
		for (int i = 0; i < b; i++) {
			cin >> s; A.push_back(s);
		}
		for (int i = 0; i < c; i++) {
			cin >> s; B[s]++;
		}
		vector<string> ans;
		vector<string>::iterator it = A.begin();
		for (it = A.begin(); it != A.end(); it++) {
			if (vis.count(*it) != 0 &&
				B.find(*it) == B.end())
			{
				ans.push_back(*it);
			}
		}

		if (ans.empty()) {
			cout << "No enemy spy";
		}
		else {
			for (int i = 0; i < ans.size(); i++) {
				cout << ans[i];
				if (i != ans.size() - 1) {
					cout << " ";
				}
			}
		}
		cout << endl;
	}

	return 0;
}

posted on 2021-07-31 10:56  itdef  阅读(135)  评论(0编辑  收藏  举报

导航