﻿HDU 1879 继续畅通工程(Kruskal)-Ocrosoft

# 继续畅通工程

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 21755    Accepted Submission(s): 9304

Problem Description

Input

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

```

Author
ZJU

Solution

Prime算法传送门：http://www.ocrosoft.com/?p=671

```#include <set>
#include <map>
#include <list>
#include <cmath>
#include <stack>
#include <queue>
#include <ctime>
#include <string>
#include <cstdio>
#include <vector>
#include <cctype>
#include <climits>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#define ms(a) memset(a,0,sizeof(a))
#define INF INT_MAX
#define MAXN 10000+10
using namespace std;
struct edge
{
int u,v,w;
bool f;
} edges[MAXN];
int n,m,cnt,sum,flag;
int pre[MAXN],son[MAXN];
void init()//初始化
{
for(int i=1; i<=n; i++)pre[i]=-1;
}
bool cmp(edge a,edge b)
{
return a.w<b.w;
}
int find(int x)
{
if(pre[x]!=x)pre[x]=find(pre[x]);//路径压缩优化
return pre[x];
}
bool Union(int x,int y)
{
int fx=find(x),fy=find(y);
pre[fx]=fy;
return true;
/*
if(fx==fy)return false;//环
else if(son[fx]>=son[fy])//加权优化
{
pre[fy]=fx;
son[fx]+=son[fy];
}
else
{
pre[fx]=fy;
son[fy]+=son[fx];
}
return true;
*/
}
int main()
{
while(cin>>n&&n)
{
cnt=0,sum=0,flag=0;
m=n*(n-1)/2;
for(int i=1; i<=n; i++)
pre[i]=i,son[i]=1;
for(int i=1; i<=m; i++)
scanf("%d%d%d%d",&edges[i].u,&edges[i].v,&edges[i].w,&edges[i].f);
sort(edges+1,edges+m+1,cmp);
for(int i=1;i<=m;i++)if(edges[i].f)Union(edges[i].u,edges[i].v);
for(int i=1;i<=m;i++)
{
if(edges[i].f)continue;
int fx=find(edges[i].u),fy=find(edges[i].v);
if(fx!=fy)pre[fx]=fy,sum+=edges[i].w;
/*
if(Union(edges[i].u,edges[i].v))
{
cnt++;
sum+=edges[i].w;
//printf("%d->%d\n",edges[i].u,edges[i].v);
}
if(cnt==n-1)//无解判断
{
flag=1;
break;
}
*/
}
printf("%d\n",sum);
}
return 0;
}
```