最小生成树 :: Prim && Kruskal 模板

Prim

模板

typedef pair<int, int> P;

int n;
int G[maxn][maxn];
int dis[maxn];

int prim(int s)
{
    int res = 0;

    priority_queue<P, vector<P>, greater<P> > qu;
    memset(dis, inf, sizeof dis);

    dis[s] = 0;
    qu.push(P(dis[s], s));

    while(qu.size())
    {
        int u = qu.top().first, v = qu.top().second;
        qu.pop();

        if(u > dis[v]) continue;

        res += u;
        dis[v] = -1;

        for(int i= 1; i<= n; i++)
        {
            if(dis[i] > G[v][i])
            {
                dis[i] = G[v][i];
                qu.push(P(dis[i], i));
            }
        }
    }

    return res;
}

注意

在主函数中读取 G 之前,应初始化为 inf。

kruskal

模板

struct Edge
{
    int s, t, cost;
    Edge(){}
    Edge(int _s, int _t, int _cost)
    :s(_s), t(_t), cost(_cost){}
    bool operator < (Edge x)
    {
        return cost < x.cost;
    }
};

int N;

Edge rode[maxm];

int Root[30], Rank[30];

void init()
{
    memset(Root, -1, sizeof Root);
    memset(Rank, 0, sizeof Rank);
}

int Uf(int x)
{
    if(Root[x] == -1) return x;
    return Root[x] = Uf(Root[x]);
}

void Union(int x, int y)
{
    x = Uf(x), y = Uf(y);
    if(x == y) return;

    if(Rank[x] < Rank[y]) Root[x] = y;
    else Root[y] = x;

    if(Rank[x] == Rank[y]) Rank[x] ++;
}

int kruskal()
{
    init();

    int tree = N, res = 0;
    for(int i= 0; ; i++)
    {
        int s = rode[i].s, t = rode[i].t, c = rode[i].cost;

        if(Uf(s) == Uf(t)) continue;
        else{
            tree --;
            res += c;
            Union(s, t);
        }

        if(tree == 1) break;
    }

    return res;
}

补充

主函数中应对 rode 数组排序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值