zoukankan      html  css  js  c++  java
  • 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)

  • 相关阅读:
    cogs 896. 圈奶牛
    bzoj 1670: [Usaco2006 Oct]Building the Moat护城河的挖掘
    bzoj 1007: [HNOI2008]水平可见直线
    bzoj 3673: 可持久化并查集 by zky
    bzoj 3545: [ONTAK2010]Peaks
    bzoj 1901: Zju2112 Dynamic Rankings
    动态 K th
    poj 2104 K-th Number
    bzoj 3657 斐波那契数列(fib.cpp/pas/c/in/out)
    青蛙的约会
  • 原文地址:https://www.cnblogs.com/Asurudo/p/10589544.html
Copyright © 2011-2022 走看看