省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N ( 1< N < 100 );随后的 N(N-1)/2 行对应村庄间道路的成本及修建状态,每行给4个正整数,分别是两个村庄的编号(从1编号到N),此两村庄间道路的成本,以及修建状态:1表示已建,0表示未建。
当N为0时输入结束。
Output
每个测试用例的输出占一行,输出全省畅通需要的最低成本。
Sample Input
3
1 2 1 0
1 3 2 0
2 3 4 0
3
1 2 1 0
1 3 2 0
2 3 4 1
3
1 2 1 0
1 3 2 1
2 3 4 1
0
Sample Output
3
1
0
思路一:1.prim()算法;2.对于value=1的情况,将路径设置为0;
#include<iostream>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const int MAX=1e2+10;
const int INF=0x3f3f3f3f;
int cost[MAX][MAX];
int mincost[MAX];
bool used[MAX];
int V;
int prim(){
memset(mincost,0,sizeof(mincost));
for(int i=1;i<=V;i++){
mincost[i]=INF;
used[i]=false;
}
mincost[1]=0;
int res=0;
while(true){
int v=-1;
for(int u=1;u<=V;u++){
if(!used[u]&&(v==-1||mincost[u]<mincost[v]))
v=u;
}
if(v==-1)
break;
used[v]=true;
res+=mincost[v];
for(int u=1;u<=V;u++){
mincost[u]=min(mincost[u],cost[v][u]);
}
}
return res;
}
void init(){
for(int i=1;i<=V;i++)
for(int j=1;j<=V;j++)
if(i==j) cost[i][j]=0;
else cost[i][j]=INF;
}
int main(){
int n;
while(~scanf("%d",&n)&&n){
V=n;
init();
int t;
int e1,e2,costa;
for(int i=1;i<=n*(n-1)/2;i++){
scanf("%d%d%d%d",&e1,&e2,&costa,&t);
cost[e1][e2]=cost[e2][e1]=costa;
}
printf("%d\n",prim());
}
}
思路二:1.Kruskal()算法;2.同思路一2.;
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX_E=1e3+10;//注意范围一定要开大
struct edge{
int u,v;
int t;
long long cost;
}es[MAX_E];
int n,m;//int V,E;//对应顶点数目和边数目
int par[MAX_E],rank[MAX_E];
bool cmp(const edge& e1,const edge& e2){
return e1.cost<e2.cost;
}
void init(int n){
for(int i=0;i<n;i++){
par[i]=i;
rank[i]=0;
}
}
int find(int x){
if(par[x]==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)
return ;
if(rank[x]<rank[y]){
par[x]=y;
}
else{
par[y]=x;
if(rank[x]==rank[y])
rank[x]++;
}
}
bool same(int x,int y){
return find(x)==find(y);
}
long long Kruskal(){
sort(es,es+m,cmp);
init(n);
long long res=0;
for(int i=0;i<m;i++){
edge e=es[i];
if(!same(e.u,e.v)){
unite(e.u,e.v);
res+=e.cost;
}
}
return res;
}
int main(){
while(~scanf("%d",&n)&&n){
m=(n-1)*n/2;
for(int i=0;i<m;i++){
cin>>es[i].u>>es[i].v>>es[i].cost>>es[i].t;
if(es[i].t==1) es[i].cost=0;
}
printf("%d\n",Kruskal());
}
return 0;
}