minimum spanning tree prime

#include<stdio.h>
#include<string.h>
using namespace std;
int map[505][505];
int v, e;
int prime()
{
  bool vis[505];
  int dist[505];
    int i,j,sum=0;
  for(i=1;i<=v;i++)
  {
    vis[i] = 0 ;
     // Assume the point numbered 1 is added to MST 
    dist[i]=map[ 1 ][i];
  }
  vis[1]=1;
  for(i=1;i<v;i++)
  {
    int k,min=0x3f3f3f3f;
    for(j=1;j<=v;j++)
    {
      if(!vis[j]&&dist[j]<min)
      {
        min=dist[j];
        k=j;
      }
    }
    /*
    A few days are added under this statistics to judge whether it constitutes MST
    */
    sum+=dist[k];
    vis[k] = 1 ;
     // Update the shortest distance between the points that have been added to the minimum spanning tree and other points below 
    for (j= 1 ;j<=v;j++ )
    {
      if(!vis[j]&&dist[j]>map[k][j])
        dist[j]=map[k][j];
    }
  }
  return sum;
}
intmain ()
{
  int n;
  int i;
  you waibu;
  scanf("%d", &n);
  while(n--)
  {
    memset(map, 0, sizeof(map));
    scanf("%d %d", &v, &e);
    
    int a, b, c;
    for(i = 0; i< e; i++)
    {
      scanf("%d %d %d", &a, &b, &c);
      map[a][b] = c;
      map[b][a] = c;
    }
    int min = 0x3f3f3f3f;
    for(i = 0; i< v; i++)
    {
      scanf("%d", &waibu);
      if(min > waibu)
        min = waibu;
    }
    printf("%d\n", prime() + min);
  }
  return 0;
}       

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324920837&siteId=291194637