D.cpp 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. const int MAXN = 101;
  4. int n;
  5. struct Edge{
  6. int x,y,z;
  7. bool operator<(const Edge&that)const{
  8. return z < that.z;
  9. }
  10. };
  11. Edge edges[MAXN*MAXN];
  12. int F[MAXN];
  13. int getf(int x){
  14. if(x == F[x]){
  15. return F[x];
  16. }else{
  17. F[x] = getf(F[x]);
  18. return F[x];
  19. }
  20. }
  21. int Kruskal(){
  22. int cnt = 0, sum = 0;
  23. for(int i = 1; i <= n * ( n - 1) / 2; i++){
  24. int t1 = getf(edges[i].x);
  25. int t2 = getf(edges[i].y);
  26. if(t1 != t2){
  27. F[t2] = t1;
  28. cnt++;
  29. sum+=edges[i].z;
  30. if(cnt>=n-1){
  31. break;
  32. }
  33. }
  34. }
  35. if(cnt == n-1){
  36. return sum;
  37. }else{
  38. return -1;
  39. }
  40. }
  41. int main(){
  42. // ifstream cin("input.txt");
  43. // ofstream cout("output.txt");
  44. while(cin >> n ){
  45. if(n == 0)break;
  46. for(int i = 1; i <= n; i++){
  47. F[i] = i;//并查集初始化
  48. }
  49. for(int i = 1; i <= n * ( n - 1) / 2; i++){
  50. int x, y, z,flag;
  51. cin >> edges[i].x >> edges[i].y >> edges[i].z>>flag;//存边
  52. if (flag == 1)//这一步很关键,表示已经修好的路
  53. edges[i].z = 0;
  54. }
  55. sort(edges+1, edges+n * ( n - 1) / 2+1);
  56. int sum = Kruskal();
  57. cout << sum << endl;
  58. }
  59. }