Prim algorithm for minimum spanning tree of 51nod 1212 without graph

Source: Internet
Author: User
The undirected graph of the N-point M-edge, with a weighted value for each edge, to find the smallest spanning tree of the graph. Input
Line 1th: 2 number n,m The middle is separated by a space, N is the number of points, and M is the number of edges. (2 <= N <=, 1 <= M <= 50000)
2-m + 1 lines: 3 number s E W per line, respectively, representing 2 vertices and weights for M-bar edges. (1 <= S, E <= n,1 <= W <= 10000)
Output
Outputs the sum of weights for all edges of the minimum spanning tree.
Input example
9
1 2 4
2 3 8
3 4 7
4 5 9 5 6 6
7 2
7 8 1
8 9 7 2
8 each
3 9
2 7 9 6
  3 6 4
4 6
1 8 8
Output example

37

#include <iostream> #include <stdio.h> #include <string.h> const int INF = 0X3F3F3F3F;
using namespace Std;
int map[1010][1010];
int dist[1010];
int vis[1010];
int n,m,x,y,z; void Init () {for (int i = 0;i <= n;i + +) for (int j = 0;j <= n;j + +) map[i][j] = map[j][i] = I
NF;
    } int Prim (int v0) {int i,j,sum = 0;
        for (int i = 1;i <= n;i + +) {Dist[i] = Map[v0][i];
    Vis[i] = V0;
    } Vis[v0] =-1;
        for (int i = 1;i < N;i + +) {int min = Inf,v =-1;
                for (int j = 1;j <= N;j + +) {if (vis[j]! =-1 && dist[j] < min) {v = j;
            min = Dist[j];
            }} if (v! =-1) {Vis[v] =-1;
            Sum + = Dist[v]; for (int j = 1;j <= N;j + +) {if (vis[j]! =-1 && map[v][j] < dist[j]) {dis
                    T[J] = Map[v][j];
                VIS[J] = v;
 }
            }       }} return sum;
        } int main () {while (~scanf ("%d%d", &n,&m)) {Init ();
            for (int i = 0;i < M;i + +) {scanf ("%d%d%d", &x,&y,&z);
        if (Map[x][y] > z) map[x][y] = map[y][x] = Z;
    } printf ("%d\n", Prim (1));
} return 0; }


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.