最小生成树模板

来源:互联网 发布:知识更新速度数据 编辑:程序博客网 时间:2024/06/05 06:29

我之前的那个用邻接矩阵的那个。。。就是会爆数据,1e5就爆了数据了。
感谢YG_PP给我的模板。。。

#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;const int MaxN = 1e5;int ans, m, n, q, father[MaxN + 5], tot;struct op{    int u, v, w;    void fu(int x, int y, int t)    {        u = x; v = y; w = t;    }}edge[MaxN + 5];void Init(){    ans = 0; tot = 0;    memset(edge, 0, sizeof(edge));    memset(father, 0, sizeof(father));    for(int i = 1; i <= n; i++) father[i] = i;}bool cmp(op x, op y){    return x.w < y.w;}void Scanf(){    int a, b, w;    for(int i = 1; i <= n * (n - 1) / 2; i++)     {        scanf("%d %d %d", &a, &b, &w);        edge[++tot].fu(a, b, w);    }    sort(edge + 1, edge + tot + 1, cmp);}int Find(int x){    if(x == father[x]) return x;    return father[x] = Find(father[x]);}void pdo(){    for(int i = 1; i <= tot; i++)    {        int u = edge[i].u, v = edge[i].v;        if(Find(u) != Find(v))        {            father[Find(u)] = v;            ans += edge[i].w;        }    }       printf("%d\n", ans);}int main(){    while(~scanf("%d", &n))    {        if(n == 0) break;        Init();        Scanf();        pdo();    }}
0 0