PAT乙级 1065 单身狗

题目描述:

“单身狗”是中文对于单身人士的一种爱称。本题请你从上万人的大型派对中找出落单的客人,以便给予特殊关爱。

输入格式:

输入第一行给出一个正整数 N(≤ 50 000),是已知夫妻/伴侣的对数;随后 N 行,每行给出一对夫妻/伴侣——为方便起见,每人对应一个 ID 号,为 5 位数字(从 00000 到 99999),ID 间以空格分隔;之后给出一个正整数M(≤10000),为参加派对的总人数;随后一行给出这 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

分析:

采用结构体存储每个人的信息,包括是否出席以及配偶id。
采用空间换时间的方法,用数组下标代表本人的id。
满足落单要求的人为:

  1. 出席。
  2. 无配偶或者配偶未出席。

中间有几个点可能要注意的是:

  1. 如果没有落单的人,仅需要输出0 。
  2. 输出的id为5位整数。

代码:

#include <cstdio>

struct person{
    int spouseId = -1;
    bool isPresent = false;
};

void printId(int a[], int n){
    for(int i = 0; i < n; i++){
        if(i == 0)
            printf("%05d", a[i]);
        else
            printf(" %05d", a[i]);
    }
}

int main()
{
    int N;
    struct person persons[100000];
    scanf("%d", &N);
    int a, b;
    //输入夫妻伴侣的对数和id
    for(int i = 0; i < N; i++){
        scanf("%d %d", &a, &b);
        persons[a].spouseId = b;
        persons[b].spouseId = a;
    }
    //输入参加派对的人数和id,并将其置为出席
    scanf("%d", &N);
    for(int i = 0; i < N; i++){
        scanf("%d", &a);
        persons[a].isPresent = true;
    }
    int count = 0;
    int singleId[100000];
    //全遍历数组,并输出出席的且无配偶或配偶未出席的人的id
    for(int i = 0; i < 100000; i++){
        //出席
        if(persons[i].isPresent){
            //无配偶或配偶未出席
            if(persons[i].spouseId == -1 || !persons[persons[i].spouseId].isPresent)
                singleId[count++] = i;
        }
    }
    //输出
    printf("%d\n", count);
    if(count != 0)
        printId(singleId, count);
    return 0;
}
发布了10 篇原创文章 · 获赞 0 · 访问量 106

猜你喜欢

转载自blog.csdn.net/qq_41421484/article/details/104065511