腾讯笔试——朋友圈

借鉴@ woloverine12138的题解
绕了一天的弯,终于绕出来。
刚开始封装成类,把每个点看成一个小集合对象,虽然没超出限制,但占用内存还是比较大,代码行数也多。
后来借鉴题解,想优化一下,想把递归找根节点这步省了,直接创建一个集合,存放当前结点的根节点,而不是父亲节点。
但是在最后统计的时候出现了问题,因为这个集合映射出来的根节点还是不能直接用。
因为我只将当前结点的祖先节点改了,它的分支节点的祖先节点没有修改,仍需利用父亲节点找到根节点。

以下是我想到代码行数最少的解法了,如果有大佬还能优化,请@我  #include<iostream>
#include<vector>
#include<unordered_map>
using namespace std;
unordered_map<int, int> Root; // fa[first] = second;
int find(int x) {
    if(Root[x] != x) Root[x] = find(Root[x]);
    return Root[x];  // 返回当前的末端节点
}
void merge(int x, int y) {
    Root[find(y)] = find(x);
}
int main() {
    int T;
    cin >> T;
    while (T--) {
        int n;
        cin >> n;
        while (n--) {
            int x, y;
            cin >> x >> y;
            if (Root.find(x) == Root.end()) Root[x] = x;   // 不存在,创建自旋结点
            if (Root.find(y) == Root.end()) Root[y] = y;
            merge(x, y);  // 合并
        }
        unordered_map<int, int> count;
        int ans = 0;
        for (auto& root : Root) {
            int f = find(root.first);
            ++count[f];
            ans = max(ans, count[f]);
        }
        cout << ans << endl;
        Root.clear();
    }
    return 0;
}


#腾讯笔试#
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务