Total Submission(s): 30061 Accepted Submission(s): 12621
Problem Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。现得到城镇道路统计表,表中列出了任意两城镇间修建道路的费用,以及该道路是否已经修通的状态。现请你编写程序,计算出全省畅通需要的最低成本。
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
思路:数据里已经连通的就用一遍unionjoin,没连通的就加进edge里。。。
代码
还是kruskal算法,感觉这个最好用。。。不懂的看前几篇
AC 312ms G++1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
using namespace std;
const int maxn=100;
int pre[maxn+3];
struct Node
{
int st,to;
int w;
}edge[maxn*(maxn-1)/2+3];
bool cmp(Node a,Node b)
{
return a.w<b.w;
}
void init(int n)
{
for (int i=1;i<=n;i++) pre[i]=i;
}
int unionfind(int x)
{
int r=x;
while (pre[r]!=r)
{
r=pre[r];
}
int i=x,j;
while (pre[i]!=r)
{
j=pre[i];
pre[i]=r;
i=j;
}
return r;
}
int unionjoin(int x,int y)
{
int fx=unionfind(x),fy=unionfind(y);
if (fx!=fy)
{
pre[fx]=fy;
return 1;
}
return 0;
}
int kruskal(int n,int m)
{
int num=n-1;
int ans=0;
for (int i=1;i<=m;i++)
{
if (unionjoin(edge[i].st,edge[i].to))
{
ans+=edge[i].w;
num--;
}
if (!num) return ans;
}
return ans;
}
int main()
{
int t,n,m,a,b,c,d,cnt;
while (~scanf("%d",&n)&&n)
{
init(n);
cnt=0;
m=n*(n-1)/2;
for (int i=1;i<=m;i++)
{
scanf("%d%d%d%d",&a,&b,&c,&d);
if (d)
{
unionjoin(a,b);
}
else
{
edge[++cnt].st=a;
edge[cnt].to=b;
edge[cnt].w=c;
}
}
sort(edge+1,edge+cnt+1,cmp);
int res=kruskal(n,cnt);
printf("%d\n",res);
}
}