Poj-2421 Constructing Roads

[题目链接]

题意: N个村庄要实现村村通,Q个村已经相通了,求剩下的村庄要实现村村通的最小花费。
思路:相通的村庄距离置为0,跑一边最小生成树就好啦。

Prim算法VSKruskal算法(感觉后者既好写,效率又高)

Prim算法:

#include
#include
#include
#include
using namespace std;
const int inf=0x3f3f3f3f;
const int Max_v=110;

int V,Q;
int dist[Max_v];
bool vis[Max_v];
int cost[Max_v][Max_v];

int Prim(){
    memset(dist,0x3f,sizeof(dist));
    memset(vis,0,sizeof(vis));
    int sum=0;
    dist[0]=0;
    while(true){
        int v=-1;
        for(int i=0;iif(!vis[i]&&dist[i]!=inf&&(v==-1||dist[i]if(v==-1)break;
        vis[v]=1;sum+=dist[v];
        for(int i=0;iif(!vis[i]&&dist[i]>cost[v][i])
                dist[i]=cost[v][i];
        }
    }
    return sum;
}

int main()
{
    scanf("%d",&V);
    int c;
    for(int i=0;ifor(int j=0;jscanf("%d",&c);
            cost[i][j]=c;
        }
    }
    scanf("%d",&Q);
    int a,b;
    for(int i=0;iscanf("%d%d",&a,&b);
        cost[a-1][b-1]=0;cost[b-1][a-1]=0;
    }
    printf("%d\n",Prim());
    return 0;
}

Kruskal算法:

#include
#include
#include
#include
using namespace std;
const int inf=0x3f3f3f3f;
const int Max_v=110;
const int Max_e=11000;

struct edge{
    int from,to,cost;
    bool operator<(const edge& e)const{
        return costint V,E,Q;
int par[Max_v];
int cost[Max_v][Max_v];

int Find(int x){
    if(par[x]==x)return x;
    return par[x]=Find(par[x]);
}

int Kruskal(){
    int ans=0,sum=0;
    for(int i=0;ifor(int i=0;iint x=Find(e[i].from);
        int y=Find(e[i].to);
        if(x!=y){
            ans++;sum+=e[i].cost;
            par[x]=y;
        }
        if(ans==V-1)break;
    }
    return sum;
}

int main()
{
    scanf("%d",&V);
    int c;
    for(int i=0;ifor(int j=0;jscanf("%d",&c);
            cost[i][j]=c;
        }
    }
    E=0;
    for(int i=0;ifor(int j=i+1;jscanf("%d",&Q);
    int a,b;
    for(int i=0;iscanf("%d%d",&a,&b);
        e[E].from=a-1;e[E].to=b-1;
        e[E++].cost=0;
    }
    printf("%d\n",Kruskal());
    return 0;
}

你可能感兴趣的:(Acm--图论,最小生成树)