小白上的cruskal简洁代码。

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<string.h>
#include<cstring>
#include<string>
#include<algorithm>
#include<math.h>
#include<queue>
#include<set>
#include<stack>
#include <string>
#include <map>
#define LL long long
#define inf 0x3f3f3f3f
#define mod 1e9+7
using namespace std;
const int maxn=1e5+5;
int n,m;///n个点,m个条边
int w[maxn],r[maxn],u[maxn],v[maxn],p[maxn];
int cmp(const int i,const int j){return w[i]<w[j];}
int Find(int x){return p[x]==x?x:p[x]=Find(p[x]);}
int Kruscal()
{
    int ans=0;
    for(int i=0;i<n;i++)p[i]=i;///初始化并查集
    for(int i=0;i<m;i++)r[i]=i;///初始化边序列,边是从0开始标记的。
    sort(r,r+m,cmp);///给边排序
    for(int i=0;i<m;i++){
        int e=r[i];int x=Find(u[e]); int y=Find(v[e]);///边e的左右端点
        if(x!=y){ans+=w[e];p[x]=y;}
    }
    return ans;
}
int main()
{

    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以直接回答,以下是CSharp实现Cruskal算法的示例代码: ```csharp using System; using System.Collections.Generic; public class Graph { public int V, E; public List<Edge> edges; public Graph(int v, int e) { V = v; E = e; edges = new List<Edge>(E); for (int i = 0; i < E; ++i) edges.Add(new Edge()); } public int Find(int[] parent, int i) { if (parent[i] == -1) return i; return Find(parent, parent[i]); } public void Union(int[] parent, int x, int y) { int xset = Find(parent, x); int yset = Find(parent, y); parent[xset] = yset; } public void KruskalMST() { Edge[] result = new Edge[V]; int e = 0; int i = 0; edges.Sort(); int[] parent = new int[V]; for (int j = 0; j < V; ++j) parent[j] = -1; while (e < V - 1) { Edge next_edge = edges[i++]; int x = Find(parent, next_edge.src); int y = Find(parent, next_edge.dest); if (x != y) { result[e++] = next_edge; Union(parent, x, y); } } Console.WriteLine("Following are the edges in " + "the constructed MST"); for (i = 0; i < e; ++i) Console.WriteLine(result[i].src + " - " + result[i].dest + ": " + result[i].weight); } } public class Edge : IComparable<Edge> { public int src, dest, weight; public int CompareTo(Edge other) { return weight.CompareTo(other.weight); } } public class Test { public static void Main() { int V = 4; int E = 5; Graph graph = new Graph(V, E); graph.edges[0].src = 0; graph.edges[0].dest = 1; graph.edges[0].weight = 10; graph.edges[1].src = 0; graph.edges[1].dest = 2; graph.edges[1].weight = 6; graph.edges[2].src = 0; graph.edges[2].dest = 3; graph.edges[2].weight = 5; graph.edges[3].src = 1; graph.edges[3].dest = 3; graph.edges[3].weight = 15; graph.edges[4].src = 2; graph.edges[4].dest = 3; graph.edges[4].weight = 4; graph.KruskalMST(); } } ``` 希望能对你有所帮助!接下来,请问你想问我什么问题?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值