并查集 将集合在逻辑上表示为树结构。

void Initial() {
    for(int i=0; i<n; i++) {
        father[i]=i;
        height[i]=0;
    }
    return ;
}

int Find(int x) {                                                                        //路径压缩
    if(x!=father[x]) {
        father[x]=Find(father[x]);
    }
    return father[x];
}

void Union(int x,int y) {                                                           //合并集合
    x=Find(x);
    y=Find(y);
    if(x!=y) {
        if(height[x]>height[y]) {
            father[y]=x;
        } else if(height[x]<height[y]) {
            father[x]=y;
        } else {
            father[y]=x;
            height[x]++;
        }
    }
    return ;                                                                        //防止成环
}



只能判断是否为连通图,或用来求图的连通分量的个数。
不能认为只有一个连通分量其一定就为树。
树是有向的。 连通分量无向!!
其可能有多个根结点。
全部评论
bool Istree() { bool f=1; int component=0; int root=0; for(int i=0; i<Max; i++) { if(!visit[i]) { continue; } if(i==father[i]) { component++; } if(Indegree[i]==0) { root++; } else if(Indegree[i]>1) { f=0; } } if(component!=1||root!=1) { f=0; } if(component==0&&root==0) { f=1; } return f; } 判断为树,一个根结点,度为0,其余结点度为1,各个结点同属一个集合!!!
点赞 回复 分享
发布于 2022-10-13 20:26 福建

相关推荐

09-25 00:00
已编辑
电子科技大学 Java
球球与墩墩:这不是前端常考的对象扁平化吗,面试官像是前端出来的 const flattern = (obj) => { const res = {}; const dfs = (curr, path) => { if(typeof curr === 'object' && curr !== null) { const isArray = Array.isArray(curr); for(let key in curr) { const newPath = path ? isArray ? `${path}[${key}]` : `${path}.${key}` : key; dfs(curr[key], newPath); } } else { res[path] = curr } } dfs(obj); return res; }
查看3道真题和解析
点赞 评论 收藏
分享
11-17 11:15
门头沟学院 Java
金山办公终于发offer了,但薪资和平台都不如已有的offer打算拒了,A不了薪资,不满意直接拒了,留给需要的人嘿嘿嘿时间线:10.14线下一面&nbsp;,10.23线上二面,下午发测评,11月1日HR面,11月14日电话谈薪,11月17日直接发offer
star__plat...:好兄弟干的好啊,解气。金山第一次笔难度高的离谱,第二次简单的离谱全A了,用人部门筛选中估计最后还是要挂我,就这今早智联招聘还给我发信息让我投
offer帮选
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务