不使用malloc的并查集算法(查找环)
创始人
2024-12-29 01:30:31
0

以下是一个不使用malloc的并查集算法,用于查找环的示例代码:

#include 
#include 

using namespace std;

class UnionFind {
private:
    vector parent;
    vector rank;

public:
    UnionFind(int n) {
        parent.resize(n);
        rank.resize(n, 0);

        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
    }

    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }

    void unite(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);

        if (rootX == rootY) {
            // x and y are already in the same set
            return;
        }

        if (rank[rootX] < rank[rootY]) {
            parent[rootX] = rootY;
        } else if (rank[rootX] > rank[rootY]) {
            parent[rootY] = rootX;
        } else {
            parent[rootY] = rootX;
            rank[rootX]++;
        }
    }
};

bool hasCycle(vector>& edges) {
    int n = edges.size();
    UnionFind uf(n);

    for (int i = 0; i < n; i++) {
        int x = edges[i][0];
        int y = edges[i][1];

        if (uf.find(x) == uf.find(y)) {
            // x and y are already in the same set, there is a cycle
            return true;
        }

        uf.unite(x, y);
    }

    return false;
}

int main() {
    vector> edges = {{0, 1}, {1, 2}, {2, 0}};
    bool hasCycle = hasCycle(edges);

    if (hasCycle) {
        cout << "The graph has a cycle." << endl;
    } else {
        cout << "The graph does not have a cycle." << endl;
    }

    return 0;
}

这个示例代码使用了一个UnionFind类来实现并查集数据结构。在构造函数中,创建了一个包含n个元素的并查集,并初始化每个元素的parent为其自身。find函数用于查找元素所属的集合,通过递归路径压缩优化来减少查找时间。unite函数用于合并两个元素所属的集合,通过rank优化来保证合并后树的平衡性。hasCycle函数用于判断给定的有向图是否存在环。

在main函数中,创建了一个包含三条边的有向图,并调用hasCycle函数来判断是否存在环。根据结果输出相应的信息。

相关内容

热门资讯

透视计算!hh poker插件... 透视计算!hh poker插件下载,hh poker辅助有用吗,揭秘攻略(有挂解密)1、hh pok...
透视辅助!hhpoker有后台... 透视辅助!hhpoker有后台操作吗,hhpoker德州机器人,科技教程(有挂教程)1、许多玩家不知...
透视计算!hhpoker视频巡... 透视计算!hhpoker视频巡查真的假的,hhpoker有后台操作吗,切实教程(有挂方法)小薇(透视...
透视挂透视!hhpoker脚本... 透视挂透视!hhpoker脚本下载,hhpoker脚本下载,2025新版教程(有挂详情)1、玩家可以...
透视有挂!hhpoker作弊码... 透视有挂!hhpoker作弊码,hhpoker真的假的,可靠教程(有挂解说)1、许多玩家不知道hhp...
透视线上!hhpoker是内部... 透视线上!hhpoker是内部控制吗,德州透视hhpoker,必备教程(有挂技巧)1、透视线上!hh...
透视新版!hhpoker免费透... 透视新版!hhpoker免费透视脚本,hhpoker怎么防作弊,技巧教程(有挂揭秘);1、玩家可以在...
透视肯定!hhpoker软件安... 透视肯定!hhpoker软件安装包,hhpkoer辅助器,可靠技巧(有挂介绍)所有人都在同一条线上,...
透视ai!hhpoker怎么破... 透视ai!hhpoker怎么破解,hhpoker真能买到挂吗,德州论坛(有挂细节);1、每一步都需要...
透视科技!hhpoker辅助软... 透视科技!hhpoker辅助软件,hhpoker外挂靠谱吗,2025新版教程(有挂揭秘);1、进入到...