7-1 畅通工程之局部最小花费问题 (35 分)
某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建快速路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全地区畅通需要的最低成本。
输入格式:
输入的第一行给出村庄数目N (1≤N≤100);随后的N(N−1)/2行对应村庄间道路的成本及修建状态:每行给出4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态 — 1表示已建,0表示未建。
输出格式:
输出全省畅通需要的最低成本。
输入样例:
4
1 2 1 1
1 3 4 0
1 4 1 1
2 3 3 0
2 4 2 1
3 4 5 0
输出样例:
3
这是一道最小生成树的板子题,使用Prim算法和Kruskal算法都可以,Prim算法和Kruskal算法详解。
这里我使用的是Prim算法,因为代码比较简短(其实还是懒)。
下面直接给出AC代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn=100+10;
const int INF=0x3f3f3f3f;
int cost[maxn][maxn];
int mincost[maxn];
bool used[maxn];
int V;
int prim()
{
memset(mincost,INF,sizeof(mincost));
memset(used,false,sizeof(used));
mincost[1]=0;
int res=0;
while(true)
{
int v=-1;
//cout<<"ggV: "<<V<<endl;
for(int u=1;u<=V;u++)
{
//cout<<"gg: "<<mincost[u]<<" "<<used[u]<<endl;
if(!used[u]&&(v==-1||mincost[u]<mincost[v]))
{
v=u;
}
}
//cout<<"ggv: "<<v<<endl;
if(v==-1) break;
used[v]=true;
res+=mincost[v];
for(int u=1;u<=V;u++)
{
mincost[u]=min(mincost[u],cost[u][v]);
}
}
return res;
}
int main()
{
for(int i=0;i<maxn;i++) memset(cost[i],INF,sizeof(cost[i]));
//for(int i=0;i<maxn;i++) cout<<"gg:: "<<cost[i][1]<<endl;
scanf("%d",&V);
for(int i=0;i<V*(V-1)/2;i++)
{
int s,t,c,f; scanf("%d %d %d %d",&s,&t,&c,&f);
cost[s][t]=c;
cost[t][s]=c;
//cout<<"输出中间值 "<<s<<" "<<t<<" "<<c<<" "<<f<<endl;
if(f) cost[s][t]=cost[t][s]=0;
}
printf("%d\n",prim());
return 0;
}