某地区经过对城镇交通状况的调查,得到现有城镇间快速道路的统计数据,并提出“畅通工程”的目标:使整个地区任何两个城镇间都可以实现快速交通(但不一定有直接的快速道路相连,只要互相间接通过快速路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建快速路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全地区畅通需要的最低成本。
输入格式:
输入的第一行给出村庄数目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
代码:
#include<iostream>
#include<stdlib.h>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int INF=0x3f3f3f3f;//无穷大
const int maxn=10000+10;
int dir[4][2]={{1,0},{0,1},{-1,0},{0,-1}};
struct Edge
{
int from;
int to;
int cost;
Edge(int x=0,int y=0,int w=0)
{
from=x;
to=y;
cost=w;
}
}edge[maxn];
int par[1000];
int Find(int x)
{
if(x==par[x])
return x;
else
return par[x]=Find(par[x]);
}
bool cmp(Edge a,Edge b)
{
return a.cost<b.cost;
}
int main()
{
int m,n;
cin>>m;
n=m*(m-1)/2;
for(int i=0;i<=1000;i++)
{
par[i]=i;
}
for(int i=0;i<n;i++)
{
int index;
cin>>edge[i].from>>edge[i].to>>edge[i].cost;
cin>>index;
if(index)
edge[i].cost=0;
}
sort(edge,edge+n,cmp);
int sum = 0;
for(int i=0;i<n;i++)
{
int x=Find(edge[i].from);
int y=Find(edge[i].to);
if(x!=y)
{
par[x]=y;
sum+=edge[i].cost;
}
}
cout<<sum<<endl;
return 0;
}