这里屯代码,毕竟新手&&蒟蒻
1 #include<cstring> 2 #include<cstdio> 3 #include<vector> 4 using namespace std; 5 const int MAXN=10000; 6 vector<int> W[MAXN],E[MAXN]; 7 int dis[MAXN],ans=0,n,m,map[MAXN][MAXN]; 8 bool vis[MAXN]={0}; 9 void add(int u,int v,int w1){ 10 E[u].push_back(v); 11 W[u].push_back(w1); 12 } 13 14 void prim(){ 15 memset(dis,127,sizeof(dis)); 16 dis[1]=0; 17 for (int i=0;i<n;i++){ 18 int min=100000,minn; 19 for (int j=1;j<=n;j++){ 20 if (dis[j]<min&&!vis[j]){ 21 min=dis[j]; 22 minn=j; 23 } 24 } 25 vis[minn]=1; 26 ans+=min; 27 for (int j=0;j<E[minn].size();j++){ 28 if (W[minn][j]<dis[E[minn][j]]){ 29 dis[E[minn][j]]=W[minn][j]; 30 } 31 } 32 } 33 } 34 35 int main(){ 36 scanf("%d",&n); 37 int u,v,w1; 38 for (int i=1;i<=n;i++){ 39 for (int j=1;j<=n;j++) scanf("%d",&map[i][j]); 40 } 41 for (int i=1;i<=n;i++) 42 for (int j=1;j<i;j++) { 43 add(j,i,map[i][j]); 44 add(i,j,map[i][j]); 45 } 46 prim(); 47 printf("%d",ans); 48 }
1 #include<cstring> 2 #include<cstdio> 3 #include<algorithm> 4 #include<vector> 5 #include<cstdlib> 6 using namespace std; 7 const int MAXN=100000; 8 vector<int> W[MAXN],E[MAXN]; 9 int dis[MAXN],ans=0,n,m,fa[MAXN]; 10 bool vis[MAXN]={0}; 11 struct edgee{ 12 int u,v,w; 13 }; 14 edgee edge[1000]; 15 16 int root(int now){ 17 if (fa[now]!=now) fa[now]=root(fa[now]); 18 return fa[now]; 19 } 20 21 void kls(){ 22 for (int i=0;i<m;i++){ 23 if (root(edge[i].u)!=root(edge[i].v)) { 24 fa[root(edge[i].u)]=edge[i].v; 25 ans+=edge[i].w; 26 } 27 } 28 } 29 30 int comp(const void*a,const void*b){ 31 edgee*aa =(edgee*)a; 32 edgee*bb =(edgee*)b; 33 return aa->w>bb->w; 34 } 35 int main(){ 36 scanf("%d%d",&n,&m); 37 int u,v,w1; 38 for (int i=1;i<=n;i++) fa[i]=i; 39 for (int i=0;i<m;i++){ 40 scanf("%d%d%d",&edge[i].u,&edge[i].v,&edge[i].w); 41 } 42 qsort(edge,m,sizeof(edge[0]),comp); 43 kls(); 44 printf("%d",ans); 45 }
一定要注意qsort的正确打开姿势
{qsort (数组名,长度,自定义函数)