ACM模板——最小生成树

int mincost[maxn];
bool used[maxn];
int MST()
{
    _for(i,0,V)
    {
        mincost[i] = INF;
        used[i] = false;
    }
    
    mincost[0] = 0;
    int res = 0;
    
    while(1)
    {
        int v = -1;
        _for(u,0,V)
            if(!used[u] && (v==-1 || mincost[u] < mincost[v]))
                v = u;
        
        if(v==-1) break;
        used[v] = true;
        res += mincost[v];
        
        _for(u,0,G[v].size())
            mincost[G[v][u].to] = min(mincost[G[v][u].to],G[v][u].cost);
    }
    return res;
}
Prim
int par[maxn]; //父亲 
int high[maxn]; //树的高度

void init(int n)
{
    _for(i,0,n)
    {
        par[i] = i;
        high[i] = 0;
    }
} 

int find(int x)
{
    return par[x] == x ? x : par[x] = find(par[x]);
}

void unite(int x,int y)
{
    x = find(x);y = find(y);
    if(x==y) return ;
    
    if(high[x]<high[y])
        par[x] = y;
    else
    {
        par[y] = x;
        if(high[x]==high[y])
            high[x] ++;
    }
}

bool same(int x,int y)
{
    return find(x) == find(y); 
}

struct tedge
{
    int u;
    int v;
    int cost;
};

vector<tedge> es;

bool cmp(const tedge& a,const tedge& b)
{
    return a.cost < b.cost;
} 
int MST()
{
    _for(i,0,V)
        _for(j,0,G[i].size())
            es.pb({i,G[i][j].to,G[i][j].cost});
    
    sort(es.begin(),es.end(),cmp);

    init(V);
    int res = 0;
    //无向图 E*2 
    _for(i,0,E*2)
    {
        tedge e= es[i];
        if(!same(e.u,e.v))
        {
            unite(e.u,e.v);
            res += e.cost;
        }
    }
    return res;
}
Kruskal(路径压缩并查集)

Prim O(|V^2|)

Kruskal O(|E|logV)

posted @ 2019-03-24 18:59  Asurudo  阅读(191)  评论(0编辑  收藏  举报