Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <algorithm>
- #include <iostream>
- #include <sstream>
- #include <string>
- #include <vector>
- #include <queue>
- #include <set>
- #include <map>
- #include <cstdio>
- #include <cstdlib>
- #include <cctype>
- #include <cmath>
- using namespace std;
- int size[100000];
- int parent [100000];
- bool cafe[100000];
- long long ans;
- pair<pair<int, int>, int> arr[400000];
- int n, m, t, a, b, c, p;
- string str;
- bool cmp(const pair<pair<int, int>, int> &a, const pair<pair<int, int>, int> &b){
- if (a.second < b.second)
- return true;
- if (a.second > b.second)
- return false;
- return a.first < b.first;
- }
- int find_set(int v) {
- if (v == parent[v])
- return v;
- return parent[v] = find_set(parent[v]);
- }
- bool union_sets(int a, int b) {
- a = find_set(a);
- b = find_set(b);
- if (a == b)
- return false;
- if (size[a] < size[b]) {
- int temp = a;
- a = b;
- b = temp;
- }
- parent[b] = a;
- size[a] += size[b];
- return true;
- }
- void MST() {
- for (int i = 0; i < n; i++) {
- if (cafe[i]) {
- parent[i] = p;
- size[p]++;
- }
- else {
- parent[i] = i;
- size[i] = 1;
- }
- }
- for (int i = 0; i < m; i++) {
- if (union_sets(arr[i].first.first, arr[i].first.second)) {
- ans += arr[i].second;
- if (size[arr[i].first.first] == n || size[arr[i].first.second] == n)
- return;
- }
- }
- }
- int main()
- {
- //freopen("input.txt","r",stdin);
- cin >> t;
- while(t--) {
- ans = 0;
- scanf("%d%d",&n,&m);
- getline(cin, str);
- getline(cin, str);
- for (int j = 0; j < n; j++)
- {
- cafe[j] = (str[j] == 'R');
- if(cafe[j]) p = j;
- size[j] = 0;
- }
- for (int j = 0; j < m; j++)
- {
- scanf ("%d%d%d", &a, &b, &c);
- a--;
- b--;
- if (c < 0) {
- ans += c;
- c = 0;
- }
- arr[j] = make_pair(make_pair(a, b), c);
- }
- sort(arr, arr + m, cmp);
- MST();
- cout << ans << endl;
- }
- // system("pause");
- return 0;
- }
Add Comment
Please, Sign In to add comment