C++代码:找出“帅到没朋友”的人

本题要求你找出那些帅到没有朋友的人。给定朋友圈数据,判断哪些人只出现在自己的朋友圈中,没有其他朋友。

输入格式:

输入第一行给出一个正整数N(≤100),是已知朋友圈的个数;随后N行,每行首先给出一个正整数K(≤1000),为朋友圈中的人数,然后列出一个朋友圈内的所有人——为方便起见,每人对应一个ID号,为5位数字(从00000到99999),ID间以空格分隔;之后给出一个正整数M(≤10000),为待查询的人数;随后一行中列出M个待查询的 ID,以空格分隔。

注意:没有朋友的人可以是根本没安装‘朋友圈’,也可以是只有自己一个人在朋友圈的人。虽然有个别自恋狂会自己把自己反复加进朋友圈,但题目保证所有K超过1的朋友圈里都至少有2个不同的人。

输出格式:

按输入的顺序输出那些帅到没朋友的人。ID间用1个空格分隔,行的首尾不得有多余空格。如果没有人太帅,则输出No one is handsome。

注意:同一个人可以被查询多次,但只输出一次。

输入样例1:

3
3 11111 22222 55555
2 33333 44444
4 55555 66666 99999 77777
8
55555 44444 10000 88888 22222 11111 23333 88888

输出样例1:

10000 88888 23333

输入样例2:

3
3 11111 22222 55555
2 33333 44444
4 55555 66666 99999 77777
4
55555 44444 22222 11111

输出样例2:

No one is handsome

思路:哈希表+并查集。

  1. 先将每个人看成一个单独的朋友圈,然后遍历每个朋友圈,将其中的人连接起来,构建并查集。
  2. 对于每个查询的 ID,用哈希表存储其所属的朋友圈。查询时,若 ID 存在哈希表中,则将其所在的朋友圈的“帅哥数”加1,否则忽略。
  3. 遍历所有朋友圈,找出“帅哥数”为0的朋友圈,输出其中的所有人 ID。

C++ 代码:

#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;

int find(vector<int>& parent, int x) {
    if (parent[x] != x) {
        parent[x] = find(parent, parent[x]);
    }
    return parent[x];
}

void unionSet(vector<int>& parent, int x, int y) {
    int rootX = find(parent, x);
    int rootY = find(parent, y);
    parent[rootX] = rootY;
}

int main() {
    int N, K, M, id;
    unordered_map<int, int> friendCircle;
    cin >> N;
    vector<int> parent(100000); // 并查集
    for (int i = 0; i < 100000; ++i) {
        parent[i] = i;
    }
    vector<int> handsomeCount(100000, 0); // 每个朋友圈的“帅哥数”

    for (int i = 0; i < N; ++i) {
        cin >> K;
        for (int j = 0; j < K; ++j) {
            cin >> id;
            if (j > 0) {
                unionSet(parent, id, parent[id - 1]); // 连接朋友圈成员
            }
        }
    }

    cin >> M;
    for (int i = 0; i < M; ++i) {
        cin >> id;
        if (friendCircle.count(id)) { // 查询 ID 是否已存在哈希表中
            handsomeCount[find(parent, id)]++; // 存在则更新“帅哥数”
        } else {
            friendCircle[id] = 1; // 不存在则加入哈希表
        }
    }

    bool flag = false;
    for (int i = 0; i < 100000; ++i) {
        if (handsomeCount[i] == 0) {
            for (int j = i; j < 100000 && find(parent, j) == i; ++j) {
                if (friendCircle.count(j)) { // 输出“帅哥数”为0的朋友圈中的所有人
                    cout << j << ' ';
                    flag = true;
                }
            }
        }
    }

    if (!flag) {
        cout << 'No one is handsome' << endl;
    } else {
        cout << endl;
    }

    return 0;
}
C++代码:找出“帅到没朋友”的人

原文地址: https://www.cveoy.top/t/topic/oWWX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录