zoukankan      html  css  js  c++  java
  • 最小生成树模板

    prim:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    using namespace std;
    const int INF = 0x3f3f3f3f;
    const int Max = 1e3;
    int mp[Max][Max],micost[Max],vis[Max];
    int V,E;
    
    int prim()
    {
        for(int i=1;i<=V;i++)
        {
            micost[i]=mp[1][i];
            vis[i]=0;
        }
        vis[1]=1;
        int res = 0;
        for(int i=1;i<=V;i++)
        {
            int mi = INF,k = -1;
            for(int j=1;j<=V;j++)
            {
                if(!vis[j]&&mi>micost[j]){
                    mi = micost[j];
                    k = j;
                }
            }
            if(k==-1) break;
            vis[k]=1;
            res += micost[k];
            for(int j=1;j<=V;j++)
            {
                if(!vis[j]&&micost[j]>mp[k][j])
                    micost[j]=mp[k][j];
            }
        }
        return res;
    }
    int main()
    {
        int from,to,cost;
        cin>>V>>E;
        for(int i=1;i<=V;i++)
            for(int j=1;j<=V;j++)
                mp[i][j]=(i==j?0:INF);
        for(int i=0;i<E;i++)
        {
            cin>>from>>to>>cost;
            mp[from][to]=cost;
            mp[to][from]=cost;//不要忘记了
        }
        int ans = prim();
        cout<<ans<<endl;
        return 0;
    }
    

    Kruskal: 

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    using namespace std;
    const int Max = 1e3;
    const int INF = 0x3f3f3f3f;
    struct node{
        int from,to,ed;
    };
    node no[Max];
    int V,E;
    int par[Max];
    int cmp(node e1,node e2)
    {
        return e1.ed<e2.ed;
    }
    void init()
    {
        for(int i=1;i<=V;i++)
            par[i]=i;
    }
    int find(int x)
    {
        if(x==par[x]) return x;
        else return par[x]=find(par[x]);
    }
    void unite(int x,int y)
    {
        x = find(x);
        y = find(y);
        if(x!=y)
            par[x]=y;
    }
    int Kruskal()
    {
        sort(no,no+E,cmp);
        init();
        int res = 0;
        for(int i=0;i<E;i++)
        {
            node e = no[i];
            if(find(e.from)!=find(e.to)){
                unite(e.from,e.to);
                res += e.ed;
            }
        }
        return res;
    }
    int main()
    {
        cin>>V>>E;
        for(int i=0;i<E;i++)
            cin>>no[i].from>>no[i].to>>no[i].ed;
        int ans = Kruskal();
        cout<<ans<<endl;
        return 0;
    }
    
  • 相关阅读:
    C++中的类模板详细讲述
    IE6
    Active Driectory 操作(转来放起来,不要丢了)
    The length of the query string for this request exceeds the configured maxQueryStringLength value
    试一下用word发布一篇文章
    各种分享api
    汇编语言程序设计 检测点1.1
    Windows下配置使用MemCached
    chrome
    ASP.NET 把集合导出为Excel的一个助手类
  • 原文地址:https://www.cnblogs.com/qie-wei/p/10160145.html
Copyright © 2011-2022 走看看