C.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int MAXN = 101;
  4. int a[MAXN][MAXN];
  5. int dis[MAXN];//每个点到源点的距离
  6. int book[MAXN];//每个点是否加入到最小生成树中
  7. int n;
  8. int Prim(){
  9. for(int i = 1; i <= n; i++){
  10. dis[i] = INT_MAX;
  11. }
  12. for(int i = 1; i <= n; i++){
  13. book[i] = 0;
  14. }
  15. dis[1] = 0;
  16. book[1] = 1;
  17. for(int i = 1; i < n; i++){
  18. int u=1, MIN = INT_MAX;//寻找离最小生成树距离最短的点
  19. for(int j = 2; j <= n; j++){
  20. if(book[j] == 0 && dis[j] < MIN){
  21. MIN = dis[j];
  22. u = j;
  23. }
  24. }
  25. book[u] = 1;
  26. for(int j = 1; j <= n; j++){
  27. if(book[j] == 0 && dis[j] > a[u][j]){
  28. dis[j] = a[u][j];
  29. }
  30. }
  31. }
  32. int sum = accumulate(dis+1, dis+n+1,0);
  33. return sum;
  34. }
  35. int main(){
  36. // ifstream cin("input.txt");
  37. // ofstream cout("output.txt");
  38. while(cin >> n ){
  39. if(n == 0)break;
  40. for(int i = 1; i <= n; i++){
  41. for(int j = 1; j <= n; j++){
  42. a[i][j] = 0;
  43. }
  44. }
  45. for(int i = 1; i <= n * ( n - 1) / 2; i++){
  46. int x, y, z;
  47. cin >> x >> y >> z;
  48. a[x][y] = a[y][x] = z;
  49. }
  50. int sum = Prim();
  51. cout << sum << endl;
  52. }
  53. }