PAT甲级——A1121 Damn Single【25】

"Damn Single (单身狗)" is the Chinese nickname for someone who is being single. You are supposed to find those who are alone in a big party, so they can be taken care of.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N (≤ 50,000), the total number of couples. Then N lines of the couples follow, each gives a couple of ID's which are 5-digit numbers (i.e. from 00000 to 99999). After the list of couples, there is a positive integer M (≤10,000) followed by M ID's of the party guests. The numbers are separated by spaces. It is guaranteed that nobody is having bigamous marriage (重婚) or dangling with more than one companion.

Output Specification:

First print in a line the total number of lonely guests. Then in the next line, print their ID's in increasing order. The numbers must be separated by exactly 1 space, and there must be no extra space at the end of the line.

Sample Input:

3
11111 22222
33333 44444
55555 66666
7
55555 44444 10000 88888 22222 11111 23333

Sample Output:

5
10000 23333 44444 55555 88888

使用couple记录是否有配偶
使用flag标记是否配偶到场
注意:最后不要输出换行,不然一旦没有输出,那么就有两个换行了!
 1 #include <iostream>
 2 #include <set>
 3 using namespace std;
 4 int main()
 5 {
 6     int n, m, boy, girl, id;
 7     int couple[100005], flag[100005];
 8     set<int>guests, res;
 9     cin >> n;
10     fill(couple, couple + 100005, -1);
11     fill(flag, flag + 100005, 0);
12     while (n--)
13     {
14         cin >> boy >> girl;
15         couple[boy] = girl;
16         couple[girl] = boy;
17     }
18     cin >> m;
19     while (m--)
20     {
21         cin >> id;
22         guests.insert(id);
23         if (couple[id] == -1)
24             continue;
25         else if (flag[id] == 0)//对偶没有来
26         {
27             flag[id] = 1;
28             flag[couple[id]] = 1;
29         }
30         else if (flag[id] == 1)//对偶来了
31         {
32             flag[id] = -1;
33             flag[couple[id]] = -1;
34         }
35     }
36     for (auto a : guests)
37     {
38         if (flag[a] != -1)
39             res.insert(a);
40     }
41     cout << res.size() << endl;
42     for (auto a : res)
43         printf("%s%05d", (a == *(res.begin()) ? "" : " "), a);
44     return 0;
45 }
原文地址:https://www.cnblogs.com/zzw1024/p/11470141.html