1. 程式人生 > >【PAT乙級】1065 單身狗

【PAT乙級】1065 單身狗

“單身狗”是中文對於單身人士的一種愛稱。本題請你從上萬人的大型派對中找出落單的客人,以便給予特殊關愛。

輸入格式:

輸入第一行給出一個正整數 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

個人思路

這題沒有什麼困難的點,注意一些細節,情侶不一定都到場,到場客人落單的有可能是單身的,也有可能是一個人來的情侶。人的資訊我用結構體存了。

程式碼實現

#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <iostream>
#define ll long long
#define ep 1e-5
#define INF 0x7FFFFFFF

using namespace std;

const int maxn = 100005;

struct Person {
    int couple;
    bool is_present;
};
Person people[maxn];

int main() {
    // 初始化
    for (int i = 0; i < maxn; i ++) {
        people[i].couple = -1;
        people[i].is_present = false;
    }
    
    // 輸入情侶
    int n;
    cin >> n;
    while (n --) {
        int cp1, cp2;
        cin >> cp1 >> cp2;
        people[cp1].couple = cp2;
        people[cp2].couple = cp1;
    }
    
    //輸入到場客人
    int m;
    cin >> m;
    for (int i = 0; i < m; i ++) {
        int id;
        cin >> id;
        people[id].is_present = true;
    }
    
    //找到落單的
    int cnt = 0, ans[maxn];
    for (int i = 0; i < maxn; i ++) {
        //到場的
        if (people[i].is_present) {
            //單身
            if (people[i].couple == -1) {
                ans[cnt++] = i;
            }
            //非單身但是伴侶不在
            else {
                int cp_id = people[i].couple;
                if (!people[cp_id].is_present)
                    ans[cnt++] = i;
            }
        }
    }
    //將答案排序
    sort(ans, ans+cnt);
    
    //輸出
    cout << cnt << endl;
    for (int i = 0; i < cnt; i ++) {
        printf("%05d", ans[i]);
        if (i < cnt-1) {
            cout << " ";
        }
    }
    
    return 0;
}

總結
學習不息,繼續加油