标签:
问题描述
#include <iostream> using namespace std; const int MAXCOST = 99999; bool prime(int **matrix, int n,int& count,int& lowcost) { int *flag = new int[n + 1]; int index; int curlowCost = MAXCOST; int *cost = new int[n + 1]; for (int i = 0; i <= n; i++) { cost[i] = MAXCOST; } //初始化 flag[1] = 1; for (int i = 2; i <= n; i++) { cost[i] = matrix[1][i]; flag[i] = 0; } for (int j = 2; j <= n; j++) { curlowCost = MAXCOST; for (int i = 1; i <= n; i++) { if (cost[i] < curlowCost && flag[i] == 0) { curlowCost = cost[i]; index = i; } } flag[index] = 1; lowcost += curlowCost; for (int k = 1; k <= n; k++) { if (flag[k] == 0 && matrix[index][k] < cost[k]) cost[k] = matrix[index][k]; } } for (int i = 1; i <= n; i++) { if (flag[i] == 1) count++; } delete[] flag; if (count == n) return true; else return false; } void main(void) { int m, n; int row, col, val; while (cin >> n>>m){ int count = 0, lowcost = 0; int **matrix; matrix = new int*[n+1]; for (int i = 0; i <= n; i++) { matrix[i] = new int[n+1]; } for (int i = 0; i <= n;i++) for (int j = 0; j <= n; j++) { matrix[i][j] = MAXCOST; } for (int i = 1; i <= m; i++) { cin >> row >> col >> val; matrix[row][col] = matrix[col][row] = val; } if (prime(matrix, n, count, lowcost)) cout << lowcost << endl; else cout << "error"; for (int i = 0; i <= n; i++) delete[] matrix[i]; } }
标签:
原文地址:http://www.cnblogs.com/tgycoder/p/5001133.html