题目描述
如题,给出一个无向图,求出最小生成树,如果该图不连通,则输出orz
输入输出格式
输入格式:
第一行包含两个整数N、M,表示该图共有N个结点和M条无向边。(N<=5000,M<=200000)
接下来M行每行包含三个整数Xi、Yi、Zi,表示有一条长度为Zi的无向边连接结点Xi、Yi
输出格式:
输出包含一个数,即最小生成树的各边的长度之和;如果该图不连通则输出orz
输入输出样例
输入样例#1: 复制
4 5
1 2 2
1 3 2
1 4 3
2 3 4
3 4 3
输出样例#1: 复制
7
说明
时空限制:1000ms,128M
数据规模:
对于20%的数据:N<=5,M<=20
对于40%的数据:N<=50,M<=2500
对于70%的数据:N<=500,M<=10000
对于100%的数据:N<=5000,M<=200000
样例解释:
所以最小生成树的总边权为2+2+3=7
//堆优化的Prim比Prim好写
#include<iostream>
#include<algorithm>
#include<queue>
#include<vector>
#include<cstring>
#include<cstdio>
#define N 5005
#define M 200005
using namespace std;
struct Edge{
int to,w,next;
inline bool operator < (const Edge &b) const {
return b.w < w;
}
}e[M << 1];
int tot,head[N];
bool vis[N];
priority_queue<Edge> q;
inline void Add_Edge(int u,int v,int w) {
e[++tot].to = v,e[tot].w = w,e[tot].next = head[u],head[u] = tot;
e[++tot].to = u,e[tot].w = w,e[tot].next = head[v],head[v] = tot;
}
inline void read(int &x) {
x = 0; int f = 1; register char c = getchar();
while(!isdigit(c)) c = getchar();
while(isdigit(c)) x = x * 10 + c - '0',c = getchar();
}
int main(int argc,char *argv[]) {
int n,m,u,v,w; read(n),read(m);
for(int i=1; i<=m; ++i) {
read(u),read(v),read(w);
Add_Edge(u,v,w);
}
int Ans = 0,Num = n - 1;
for(int i=head[1]; i; i=e[i].next) q.push(e[i]);
vis[1] = 1;
while(Num && !q.empty()) {
Edge Now = q.top(); q.pop();
if(vis[Now.to]) continue;
Ans += Now.w,Num--;
int u = Now.to; vis[u] = 1;
for(int i=head[u]; i; i=e[i].next) {
int v = e[i].to;
if(!vis[v]) q.push(e[i]);
}
}
printf("%d\n",Ans);
return 0;
}
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#define N 5005
#define M 200005
using namespace std;
int fa[N];
struct Edge{
int u,v,w;
inline bool operator < (const Edge &b) const {
return w < b.w;
}
}e[M];
int Find(int x) {
if(x == fa[x]) return x;
else return fa[x] = Find(fa[x]);
}
inline void read(int &x) {
x = 0; int f = 1; register char c = getchar();
while(!isdigit(c)) c = getchar();
while(isdigit(c)) x = x * 10 + c - '0',c = getchar();
}
int main(int argc,char *argv[]) {
int n,m; read(n),read(m);
for(int i=1; i<=n; ++i) fa[i] = i;
for(int i=1; i<=m; ++i)
read(e[i].u),read(e[i].v),read(e[i].w);
sort(e + 1, e + m + 1);
int Num = 0,Ans = 0;
for(int i=1; i<=m; ++i) {
int u = e[i].u,v = e[i].v,w = e[i].w;
u = Find(u),v = Find(v);
if(u == v) continue;
++Num,fa[v] = u,Ans += w;
if(Num == n-1) break;
}
printf("%d\n",Ans);
return 0;
}