Title Description
Title, give an undirected graph, find the minimum spanning tree, if the graph is not connected, then output ORZ input format input and output format :
The first line consists of two integers n, M,
Indicates that the graph has a total of n nodes and M-bar without edges. (n<=5000,m<=200000)
The next m line contains three integers of Xi, Yi, Zi,
Indicates that there is a non-Zi Edge junction XI, Yi output format for the length of the line:
The output contains a number, the sum of the lengths of the edges of the smallest spanning tree, and if the graph is not connected to the general output Orz input and Output sample Input Sample #:
4 5
1 2 2
1 3 2
1 4 3
2 3 4
3 4 3 Output Example # #:
7 Code Kruskal (algorithm based on the and check set)
#include <cstdio> #include <algorithm> using namespace std;
const int m=200005,n=5005;
int N,m,ans,h[n],fa[n],t,edge; struct node{int u,v,w;}
E[M];
inline int read () {int sum=0; char Ch=getchar (); while (ch> ' 9 ' | |
ch< ' 0 ') Ch=getchar ();
while (ch<= ' 9 ' &&ch>= ' 0 ') Sum=sum*10+ch-48,ch=getchar ();
return sum;
} BOOL CMP (node A,node b) {return a.w<b.w;} int find (int x) {if (fa[x]!=x) Fa[x]=find (fa[x]);
return fa[x];
} int main () {int u,v,w;
N=read (), M=read ();
for (int i=1;i<=n;i++) fa[i]=i;
for (int i=1;i<=m;i++) {e[i].u=read (), E[i].v=read (), E[i].w=read ();
} sort (e+1,e+m+1,cmp);
for (int i=1;i<=m;i++) {int u=e[i].u;
int v=e[i].v;
int W=E[I].W;
if (Find (U) ==find (v)) continue;
Fa[find (u)]=v;
Edge++;ans+=w;
if (edge==n-1) {printf ("%d", ans);
return 0;
}} printf ("Orz"); RetUrn 0; }
Prim (DJ-based algorithm)
#include <cstdio>
using namespace std;
const int MAXN=0X7FFFFFFF;
int d[5005],w[5005][5005],v[5005];
int m,n,x,y,z,min1,t,sum;
int main ()
{
scanf ("%d%d", &n,&m);
for (int i=1;i<=m;i++)
{
scanf ("%d%d%d", &x,&y,&z);
if (w[x][y]==0| | W[x][y]>z)
{
w[x][y]=z;
w[y][x]=z;
}
}
for (int i=1;i<=n;i++) D[I]=MAXN;
d[1]=0;
for (int i=1;i<=n;i++)
{
min1=maxn;
for (int j=1;j<=n;j++)
{
if (v[j]==0&&d[j]<min1)
{
t=j;
MIN1=D[J];
}
}
V[t]=1;
sum=sum+min1;
for (int j=1;j<=n;j++)
if (V[j]==0&&w[t][j]!=0&&d[j]>w[t][j])
d[j]=w[t][j];
}
printf ("%d", sum);
return 0;
}