PAT乙级 ——单身狗

题目描述
“单身狗” 是中文对于单身人士的一种爱称。

本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱。

输入格式
输入第一行给出一个正整数 N,是已知夫妻/伴侣的对数;
随后 N 行,每行给出一对夫妻/伴侣——为方便起见,每人对应一个 ID 号,为 5 位数字(从 00000 到 99999),ID 间以空格分隔;
之后给出一个正整数 M,为参加派对的总人数;
随后一行给出这 M 位客人的 ID,以空格分隔。

题目保证无人重婚或脚踩两条船。

输出格式
首先第一行输出落单客人的总人数;
随后第二行按 ID 递增顺序列出落单的客人。ID 间用 1 个空格分隔,行的首尾不得有多余空格。

输入样例
3
11111 22222
33333 44444
55555 66666
7
55555 44444 10000 88888 22222 11111 23333

输出样例
5
10000 23333 44444 55555 88888

数据范围
N ≤ 50 000
M ≤ 10 000


题解
STL:

解题步骤

  1. 先用 map 对每一对情侣进行相互映射;
  2. 再用 set 记录要参加派对的人;
  3. 最后枚举所有 set 中的元素,若其配偶不在 set 中,则添加到 ans 中去;
#include <iostream>
#include <unordered_map>
#include <vector>
#include <set>
using namespace std;

int n, m;
vector<string> ans;
unordered_map<string, string> H;
set<string> S;

int main()
{
    
    
	cin >> n;
	
	for (int i = 1; i <= n; i ++)
	{
    
    
		string a, b;
		cin >> a >> b;
		H[a] = b, H[b] = a;
	}
	
	cin >> m;
	
	for (int i = 1; i <= m; i ++) 
	{
    
    
		string s;
		cin >> s;
		S.insert(s);
	}
	
	for (auto &x : S)
		if(!S.count(H[x])) ans.push_back(x);
		
	cout << ans.size() << endl;
	
	bool flag = true;
	for (int i = 0; i < ans.size(); i ++)
		if(flag) cout << ans[i], flag = false;
		else cout << ' ' << ans[i];
	
	return 0;		
}

错解:测试点 2 段错误,然而找不出错

#include <iostream>
#include <map>
#include <set>
using namespace std;

int n, m;
map<string, string> H;
set<string> S;

int main()
{
    
    
	cin >> n;
	
	for (int i = 1; i <= n; i ++)
	{
    
    
		string a, b;
		cin >> a >> b;
		H[a] = b, H[b] = a;
	}
	
	cin >> m;
	
	for (int i = 1; i <= m; i ++) 
	{
    
    
		string s;
		cin >> s;
		S.insert(s);
	}
	
	for (auto &x : S)
		if(S.count(H[x])) 
		{
    
    
			S.erase(S.find(x));
			S.erase(S.find(H[x]));
			if(S.empty()) break;
		}
		
	cout << S.size() << endl;
	
	bool flag = true;
	for (auto &x : S)
		if(flag) cout << x, flag = false;
		else cout << ' ' << x;
	
	return 0;		
}

猜你喜欢

转载自blog.csdn.net/weixin_46239370/article/details/113853007