天天看点

PAT (Basic Level) Practice 1065

1065 单身狗(25 分)

“单身狗”是中文对于单身人士的一种爱称。本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱。

输入格式:

输入第一行给出一个正整数 N(≤ 50 000),是已知夫妻/伴侣的对数;随后 N 行,每行给出一对夫妻/伴侣——为方便起见,每人对应一个 ID 号,为 5 位数字(从 00000 到 99999),ID 间以空格分隔;之后给出一个正整数 M(≤ 10 000),为参加派对的总人数;随后一行给出这 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
           

分析:用map储存所有人的配偶和宾客到场情况,之后检测所有人的配偶是否到场(若不存在则视为未到场),如为未到场则送入set中。最后输出set的大小及内容。

代码: 

#include<iostream>
#include<set>
#include<map>
using namespace std;
map<int, int> couple;
map<int, bool> isArrival;
set<int> single;
int main() {
	int N;
	cin >> N;
	for (int i = 0; i < N; i++) {
		int temp1, temp2;
		cin >> temp1 >> temp2;
		couple[temp1] = temp2;
		couple[temp2] = temp1;
	}
	int M;
	cin >> M;
	for (int i = 0; i < M; i++) {
		int temp;
		cin >> temp;
		isArrival[temp] = true;
	}
	for (map<int, bool>::iterator it = isArrival.begin(); it != isArrival.end(); it++) {
		if (isArrival[couple[(*it).first]] == false) {
			single.insert((*it).first);
		}
	}
	cout << single.size() << endl;
	bool isFirst = true;
	for (set<int>::iterator it = single.begin(); it != single.end(); it++) {
		if (isFirst == true) {
			printf("%05d", (*it));
			isFirst = false;
		}else {
			printf(" %05d", (*it));
		}
	}
	return 0;
}