最小產生樹

來源:互聯網
上載者:User

標籤:tor   pen   and   ini   eve   blog   cte   gif   演算法   

Kruskal:適用稀疏圖
需要Union_Find_Set(並查集)

class Kruskal {#define Kruskal_MAXN 100#define Kruskal_MAXM 10005public:    Union_Find_Set ufs;    int x[Kruskal_MAXM], y[Kruskal_MAXM], w[Kruskal_MAXM], N, M;    Kruskal() {        N = 0;        M = 0;    }    void clear() {        N = 0;        M = 0;    }    void addEdge(int a, int b, int c) {        x[M] = a;        y[M] = b;        w[M] = c;        M++;        x[M] = b;        y[M] = a;        w[M] = c;        M++;    }    void sort(int l, int r) {        int i = l, j = r, m = w[(l + r) >> 1], t;        do {            while (w[i] < m) {                i++;            }            while (m < w[j]) {                j--;            }            if (i <= j) {                t = x[i];                x[i] = x[j];                x[j] = t;                t = y[i];                y[i] = y[j];                y[j] = t;                t = w[i];                w[i] = w[j];                w[j] = t;                i++;                j--;            }        } while (i <= j);        if (l < j) {            sort(l, j);        }        if (i < r) {            sort(i, r);        }    }    int MST() {        sort(0, M - 1);        ufs.clear(N + 1);        int cnt = 0, ret = 0;        for (int i = 0; i < M; i++) {            if (cnt == N - 1) {                return ret;            }            if (ufs.getFather(x[i]) != ufs.getFather(y[i])) {                ufs.merge(x[i], y[i]);                ret += w[i];                cnt++;            }        }        if (cnt == N - 1) {            return ret;        } else {            return -1;        }    }};
View Code

Kruskal_MAXN:最大點數
Kruskal_MAXM:最大邊數
N:點數
void addEdge(int a, int b, int c):添加一條ab之間長度為c的邊
int MST():最小產生樹

prim:適用稠密圖(暫無)

線性隨機演算法(暫無)

最小產生樹

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.