单点时限: 2.0 sec
内存限制: 256 MB
Partychen is working as system administrator and is planning to establish a new network in his company. There will be N hubs in the company, they can be connected to each other using cables. Since each worker of the company must have access to the whole network, each hub must be accessible by cables from any other hub (with possibly some intermediate hubs).
Since cables of different types are available and shorter ones are cheaper, it is necessary to make such a plan of hub connection, that the cost is minimal. partychen will provide you all necessary information about possible hub connections. You are to help partychen to find the way to connect hubs so that all above conditions are satisfied.
输入格式
The first line of the input contains two integer numbers: N - the number of hubs in the network (2 <= N <= 1000) and M - the number of possible hub connections (1 <= M <= 15000). All hubs are numbered from 1 to N. The following M lines contain information about possible connections - the numbers of two hubs, which can be connected and the cable cost required to connect them. cost is a positive integer number that does not exceed 106. There will always be at least one way to connect all hubs.
输出格式
Output the minimize cost of your hub connection plan.
样例
input
4 6
1 2 1
1 3 1
1 4 2
2 3 1
3 4 1
2 4 1
output
3
Hint
We can build net from 1 to 2 to 3 to 4,then we get the cost is 3.Of course you can get 3 by other way.
思路:题解:题目大意是有n个顶点,m条边,使图连通,使边权和最小,不构成回路
kruskal算法:按边权从小到到排序,顺序将边加入图中,若图中两点不连通则加入,否则就不考虑,(判断两点是否在图中中并查集,并查集的主要功能就是合并和查找的功能),最终就可以解答此题,找到最小的边权的连通图。
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
struct g {
int a,b;
int cost;
};
int father[1001];
bool cmp(g x,g y) {
return x.cost<y.cost;
}
int findfather(int x) {
int a=x;
while(x!=father[x]) {
x=father[x];
}
while(a!=father[a]) {//路径压缩
int z=a;
a=father[a];
father[z]=x;
}
return x;
}
int main() {
int n,m;
cin>>n>>m;
g G[m+1];
for(int i = 0; i < m; i++) {
cin>>G[i].a>>G[i].b>>G[i].cost;
}
for(int i = 1; i <= n; i++)
father[i]=i;
sort(G,G+m,cmp);
int ans=0;
for(int i = 0; i < m; i++) {
int fath_a=findfather(G[i].a);
int fath_b=findfather(G[i].b);
if(fath_a!=fath_b) {
ans+=G[i].cost;
father[fath_a]=fath_b;
}
}
cout<<ans<<endl;
return 0;
}