leetcode684.冗余连接

依旧是并查集问题,这道题目正好给定顶点数目和边的数目相等,只要找到其中的一条边删除将图转化为树就行,而这个多余的边起始就是并查集的添加过程中二者是同一个根(两个顶点早已经联通了),这时直接返回这条边就行

注意这题中的顶点编号从1开始,为保证一致性,father数组大小为n+1,0索引不使用

cpp 复制代码
class Solution {
private:
    vector<int> father;

    void init() {
        for(int i=0;i<father.size();i++)
            father[i]=i;
    }

    int find(int v) {
        return v==father[v]?v:father[v]=find(father[v]);
    }

    bool isSame(int u,int v) {
        u=find(u);
        v=find(v);
        return u==v;
    }

    bool join(int u,int v) {
        u=find(u);
        v=find(v);
        if(u==v)
            return false;
        else{
            father[v]=u;
            return true;
        }
    }
public:
    vector<int> findRedundantConnection(vector<vector<int>>& edges) {
        int n=edges.size();
        this->father=vector<int>(n+1);
        this->init();

        for(int i=0;i<n;i++){
            int u=edges[i][0];
            int v=edges[i][1];
            if(!this->join(u,v))
                return {u,v};
        }
        return {};
    }
};
相关推荐
努力学习的小廉1 小时前
我爱学算法之—— 模拟(下)
c++·算法
海琴烟Sunshine2 小时前
Leetcode 26. 删除有序数组中的重复项
java·算法·leetcode
PAK向日葵2 小时前
【算法导论】NMWQ 0913笔试题
算法·面试
PAK向日葵2 小时前
【算法导论】DJ 0830笔试题题解
算法·面试
PAK向日葵2 小时前
【算法导论】LXHY 0830 笔试题题解
算法·面试
麦麦麦造3 小时前
DeepSeek突然发布 V3.2-exp,长文本能力加强,价格进一步下探
算法
lingran__4 小时前
速通ACM省铜第十七天 赋源码(Racing)
c++·算法
MobotStone5 小时前
手把手教你玩转AI绘图
算法
CappuccinoRose5 小时前
MATLAB学习文档(二十二)
学习·算法·matlab
学c语言的枫子6 小时前
数据结构——基本查找算法
算法