1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
| #include<bits/stdc++.h> using namespace std; const int inf = 0x3f3f3f3f; const int maxe = 2e5 + 100; struct edge{ int v,w,next; }e[maxe<<1]; int head[5020],dis[5020],n,m,now,cnt,ans; bool vis[5020]; void add(int u,int v,int w){ cnt++; e[cnt].v=v; e[cnt].w=w; e[cnt].next=head[u]; head[u]=cnt; } void init(){ scanf("%d%d", &n, &m); int u, v, w; for(int i=1;i<=m;i++){ scanf("%d%d%d", &u, &v, &w); add(u,v,w),add(v,u,w); } } int prim(int a){ memset(dis,inf,sizeof(dis)); dis[a] = 0; now = a; for (int i = head[a]; i; i = e[i].next) dis[e[i].v] = min(dis[e[i].v], e[i].w); for (int cnt = 1; cnt <= n - 1;cnt++){ int minn = inf; vis[now] = true; for (int i = 1; i <= n;i++){ if (!vis[i] && minn > dis[i]){ minn = dis[i]; now = i; } } ans += minn; for (int i = head[now]; i; i = e[i].next){ if (!vis[e[i].v]) dis[e[i].v] = min(dis[e[i].v], e[i].w); } } return ans; } int main(){ init(); printf("%d",prim(1)); system("pause"); return 0; }
|