定义一个map<int,int>couple来存储两个人的夫妻关系 。另外定义一个set,在输入M位客人的过程中,如果该客人没有配偶,直接将ID号加入set中;如果有配偶,在set中查找是否包含其配偶的ID,如果不包含,将该客人的ID号加入set中;如果包含,在set中删除其配偶的ID 。最后set中储存的就是落单的客人,输出即可。
代码如下:
#include<bits/stdc++.h>
using namespace std;
int main(){
int N,M;
scanf("%d",&N);
map<int,int>couple;//存储夫妻关系
while(N--){
int a,b;
scanf("%d%d",&a,&b);
couple[a]=b;
couple[b]=a;//互为键和映射
}
scanf("%d",&M);
set<int>s;
while(M--){
int c;
scanf("%d",&c);
if(couple.find(c)==couple.end()){ //如果该客人没有配偶
s.insert(c);//直接将ID号加入set中
}
else{
auto it=s.find(couple[c]);//在set中查找是否包含其配偶的ID
if(it==s.end())//不包含其配偶的ID
s.insert(c);//直接将ID号加入set中
else//包含其配偶的ID
s.erase(it);//在set中删除其配偶的ID
}
}
printf("%d\n",s.size());
for (auto it=s.begin(); it!=s.end();it++) {
if (it != s.begin())
printf(" ");
printf("%05d", *it);
}
}