码迷,mamicode.com
首页 > 编程语言 > 详细

prim算法

时间:2017-09-14 21:34:57      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:put   def   pre   byte   cte   node   weight   i++   return   

#include <iostream>
#include <string.h>
#include <stdlib.h>
using namespace std;
/**********************************************************
* in this program, you need to input the map information, like this:
* x y weight
* x represents a city, y is the same as x
* first please input the quantity of city and the number of origin and the number of relationship of city
*/
#define MaxNode 20
void Prim(int n, int u0, int c[][])
{
bool s[n];
int closet[n];
double lowcost[n];
s[u0] = true;
for(int i=0; i<n; i++)
{
if(i!=u0)
{
lowcost[i] = c[u0][i];
closet[i] = u0;
s[i] = false;
}
}
for( int i=0; i<n; i++)
{
double temp = 0X7ffffff; //the max value of int type in the machine of 32 byte
int t = u0;
for(int j=0; j<n; j++)
{
if(!s[j]&&lowcost[j]<temp)
{
t = j;
temp = lowcost[j];
}
}

if(t==u0)
break;
s[t] = true;
for(int j=0; j<n; j++)
{
if(!s[J]&&lowcost[j]>u[t][j])
{
lowcost[j] = u[t][j];
closet[j] = t;
}
}
}
for(int i=0; i<n; i++)
{
if(s[i]==false)
{
cout << "figure is not connected";
return;
}

}
for(int i=0; i<n; i++)
cout << closet[i] << " " << i << " " << lowcost[i] << endl;
}


int main()
{

int n, origin;
cin >> n >> origin;
int mem[n][n];
int x, y, weight;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
{
cin >> x >> y >> weight;
mem[x][y] = mem[y][x] = weight;
}
Prim(n, origin, mem);
return 0;
}

prim算法

标签:put   def   pre   byte   cte   node   weight   i++   return   

原文地址:http://www.cnblogs.com/1915884031A-qqcom/p/7522803.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!