Problem Description
Economic times these days are tough, even in Byteland. To reduce the operating costs, the government of Byteland has decided to optimize the road lighting. Till now every road was illuminated all night long, which costs 1 Bytelandian Dollar per meter and day. To save money, they decided to no longer illuminate every road, but to switch off the road lighting of some streets. To make sure that the inhabitants of Byteland still feel safe, they want to optimize the lighting in such a way, that after darkening some streets at night, there will still be at least one illuminated path from every junction in Byteland to every other junction.
What is the maximum daily amount of money the government of Byteland can save, without making their inhabitants feel unsafe?
Input
The input file contains several test cases. Each test case starts with two numbers m and n, the number of junctions in Byteland and the number of roads in Byteland, respectively. Input is terminated by m=n=0. Otherwise, 1 ≤ m ≤ 200000 and m-1 ≤ n ≤ 200000. Then follow n integer triples x, y, z specifying that there will be a bidirectional road between x and y with length z meters (0 ≤ x, y < m and x ≠ y). The graph specified by each test case is connected. The total length of all roads in each test case is less than 231.
Output
For each test case print one line containing the maximum daily amount the government can save.
Sample Input
7 11
0 1 7
0 3 5
1 2 8
1 3 9
1 4 7
2 4 5
3 4 15
3 5 6
4 5 8
4 6 9
5 6 11
0 0
Sample Output
51
思路
标准的最小生成树问题,任意连个路口之间均有路灯,即任意两个路口连通。
需要注意的是本题问的是节省了多少钱,要拿原来的钱减一下。
此解采用了kruskal算法 点击查看kruskal算法
代码
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
struct edge //边
{
int from,to,dis;
}e[200001];
int fa[100001]; //父节点
int n,m,cnt;
long long int ans;
bool cmp(edge a,edge b)
{
return a.dis<b.dis; //用于排序
}
int getfa(int i) //寻找根节点
{
if(fa[i]==i)
return i;
return getfa(fa[i]);
}
void unionn(int u,int v)
{
fa[getfa(u)]=getfa(v); //合并
}
void kruskal()
{
for(int i=1;i<=n;i++) //初始将自己设为自己的父节点
fa[i]=i;
sort(e+1,e+1+m,cmp); //排序
for(int i=1;i<=m;i++)
{
if(cnt==n-1) //共n-1条边
return;
if(getfa(e[i].from)!=getfa(e[i].to))//如果根节点相同,则说明已经成环
{
unionn(e[i].to,e[i].from); //使用一条边后,将两端点设置为子节点和父节点
ans+=e[i].dis;
cnt++;
}
}
}
int main()
{
while(1)
{
cin>>n>>m;
if(n==0&&m==0)
return 0;
long long int sum=0;
memset(fa,0,sizeof(fa)); //重置数据
cnt=0;
ans=0;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&e[i].from,&e[i].to,&e[i].dis);
sum+=e[i].dis; //计算总距离
}
kruskal();
cout<<sum-ans<<endl;
}
return 0;