Minimum spanning tree ----------- liaison

Tyvj is one year old, and the website has increased from the first few users to tens of thousands of users. With the gradual growth of the Tyvj website, the number of administrators is also increasing. Now you are a liaison of Tyvj management, I hope you find some communication channels so that the administrator can contact each other (either directly or indirectly). The communication channels involved in this question are bidirectional. Tyvj is a non-profit website with no excessive profits, so you need to keep the costs as low as possible. At present, you already know that Tyvj's communication channels are divided into two categories, one is a mandatory communication channel, no matter how much the price is, you need to choose all of them; and the other is a selective communication channel, you can choose from Pick some communication channels to contact as the final administrator. The data guarantees that the given communication channel allows all administrators to communicate. Note: For some two administrators u, vu, v

, There may be multiple communication channels between them, your program should accumulate all u, vu, v

Must pass between channels. Two integers n, mn, m in the first line of the input format

Indicates that Tyvj has a total of nn

Administrators, mm

Communication channels; second line to m + 1m + 1

Rows, four non-negative integers per row, p, u, v, wp, u, v, w

When p = 1p = 1

, Indicates that this communication channel is a required communication channel; when p = 2p = 2

, Indicates that this communication channel is a selective communication channel; u, v, wu, v, w

Indicates that this message describes u, vu, v

Communication channel between administrators, uu

Can receive vv

Information, vv

Can also receive uu

Information, ww

Indicates the cost. The output format is an integer that represents the minimum communication cost. Data range 1≤n≤20001≤n≤2000

1≤m≤100001≤m≤10000

Sample input: 5 6
1 1 2 1
1 2 3 1
1 3 4 1
1 4 1 1
2 2 5 10
2 2 5 5
Sample output: 9

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 2010, M = 10010;
int n, m;
int p[N];
struct Edge{
 int a, b, w;
 bool operator < (const Edge &t)const{
     return w < t.w; 
 }
}e[M];
int find(int x){
 if (p[x] != x)    p[x] = find(p[x]);
 return p[x];
}
int main(){
 cin >> n >> m;
 for (int i = 1; i <= n; i ++)   p[i] = i;
  int res = 0, k = 0;
 for (int i = 0; i < m; i ++){
  int t, a, b, w;
  cin >> t >> a >> b >> w;
  if (t == 1){
   res  += w;
   p[find(a)] = find(b);
  }
  else    e[k ++] = {a, b, w};
 }
  sort(e, e + k);
  for (int i = 0; i < k; i ++){
  int a = find(e[i].a), b = find(e[i].b);
  if (a != b){
   res += e[i].w;
   p[a] = b;
  }
 }
  cout << res << endl;
  return 0;
}

164 original articles published · Like 112 · Visits 6777

Guess you like

Origin blog.csdn.net/qq_45772483/article/details/105408792