图算法总结---Prime算法

来源:互联网 发布:青蛙寿命 知乎 编辑:程序博客网 时间:2024/05/23 14:32
//// Created by liyuanshuo on 2017/3/13.//#include <iostream>const int max_cost = 0x7fffffff;//int graph[10010][10010];int prime(int graph[][10010], int n){int lowcost[10010];int mst[10010];int i, j, minn, minID, sum = 0;for ( i =2 ; i<= n ; i++){lowcost[i] = graph[1][i];mst[i] = 1;}mst[1] = 0;for( i = 2 ; i <= n ; i++ ){minn = max_cost;minID = 0;for ( j = 2 ;  j <= n ; j++ ){if( lowcost[j] < minn && lowcost[j] != 0 ){minn = lowcost[j];minID = j;}}// ouput the min distance between two sidesstd::cout<<"v "<<mst[minID]<<"----v"<<minID<<" = "<<minn<<std::endl;sum += minn;lowcost[minID] = 0;for ( j = 2 ;  j <= n ; j++ ){if( graph[minID][j] < lowcost[j] ){lowcost[j] = graph[minID][j];mst[j] = minID;}}}return sum;}//input the information of the graph, and use the prime_algorithmvoid using_prime( int graph[][10010] ){int i, j, k, m, n;int cost;std::cin>>m>>n;for ( i=1 ; i<= m ; i++ ){for ( j=1 ; j<=m ; j++){graph[i][j] = max_cost;}}for ( k=1 ; k<=n ; k++ ){std::cin>>i>>j>>cost;graph[i][j] = cost;graph[j][i] = cost;}cost = prime (graph, m);std::cout<<"min coat is : "<<cost<<std::endl;}

0 0