方法1
#include <stdio.h>
#define BLANK -1
#define SIGNED -2
#define SINGLE -3
int main()
{
int couple[100000], count = 0, N, M, ID1, ID2;
for(int i = 0; i < 100000; i++)
couple[i] = BLANK;
/* Read 'couple-list', every pair of 'index' and 'value' are a couple. */
scanf("%d", &N);
for(int i = 0; i < N; i++)
{
scanf("%d %d", &ID1, &ID2);
couple[ID1] = ID2;
couple[ID2] = ID1;
}
scanf("%d", &M);
for(int i = 0; i < M; i++) /* Read guest list. */
{
scanf("%d", &ID1);
if(couple[ID1] >= 0) /* If one has a mate */
couple[ID1] = SIGNED; /* set SIGNED */
else /* Else: not in the 'couple-list' */
couple[ID1] = SINGLE, count++; /* set SINGLE */
}
/* If couple[ID] is >= 0 (but not signed) but couple[couple[ID]] == SIGNED
* (signed in), this means 'ID' didn't come but his/her mate did.
* So his/her mate is alone in the party, set to SINGLE. */
for(int i = 0; i < 100000; i++)
if(couple[i] >= 0 && couple[couple[i]] == SIGNED)
couple[couple[i]] = SINGLE, count++;
/* Those whose value is SINGLE is either a bachelor or came alone */
printf("%d\n", count);
for(int i = 0; i < 100000; i++)
if(couple[i] == SINGLE)
printf("%05d%c", i, --count ? ' ' : '\0');
return 0;
}
方法2
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main(){
map<string, pair<string,int>> s, res; //s用于判断是否单身
map<string, pair<string,int>>::iterator it;
int n, m, count = 0;
string r, l;
cin >> n;
while (n--) {
cin >> l >> r;
s[l].first = r; //存入伴侣信息
s[r].first = l;
}
cin >> m;
for (int i = 0; i < m; i++) {
cin >> l;
s[l].second++;
}
for (it = s.begin(); it != s.end(); it++) {
if (it->second.second && !s[it->second.first].second) { //逻辑判断:自己出席了会议,伴侣没有
count++; //记录单身狗数目
res[it->first].second++; //将符合条件的人存到res中
}
}
cout << count << endl;
if (count) { //注意count为0时,就不用输出ID了,否则测试点2出现段错误、运行超时
it = res.begin();
cout << it++->first;
for (; it != res.end(); it++) {
cout << " " << it->first;//这样能输出空格
}
}
return 0;
}