题目


解法1

点击查看代码
#include <iostream>
#include <vector>
#include <set>
#include <unordered_map>
#include <algorithm>
using namespace std;

int main() {
    int n;
    scanf("%d", &n);
    unordered_map<int, int> couples; // 存储每对夫妻的映射关系

    for (int i = 0; i < n; i++) {
        int a, b;
        scanf("%d %d", &a, &b);
        couples[a] = b;
        couples[b] = a;
    }

    int m;
    scanf("%d", &m);
    set<int> guests; // 使用集合存储客人,方便查找和排序
    for (int i = 0; i < m; i++) {
        int id;
        scanf("%d", &id);
        guests.insert(id);
    }

    set<int> lonely; // 存储单身狗的ID
    for (int id : guests) {
        if (couples.find(id) == couples.end() || guests.find(couples[id]) == guests.end()) {
            lonely.insert(id); // 如果该客人没有伴侣或伴侣不在场,则加入单身狗集合
        }
    }

    printf("%d\n", int(lonely.size()));
    bool first = true;
    for (int id : lonely) {
        if (!first) printf(" "); // 除了第一个外,其他的都先打印空格
        printf("%05d", id); // 输出5位数,不足补零
        first = false;
    }

    return 0;
}