Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <algorithm>
- #include <stack>
- #include <cstring>
- #include <queue>
- #define ll long long
- #define MAX(a,b) (a)>(b)?(a):(b)
- #define MIN(a,b) (a)>(b)?(b):(a)
- #define pll pair<ll, ll>
- using namespace std;
- typedef struct route {
- int u, v;
- ll cost;
- route(int a, int b, ll c): u(a), v(b), cost(c){}
- bool operator < (const route& a) const {
- return this->cost > a.cost;
- }
- };
- int N, M;
- char univ[1234];
- priority_queue<route, vector<route>, less<route>> G;
- int parent[1234], _rank[1234];
- bool vi[1234];
- void init() {
- for (int i = 0; i <= N; i++) {
- parent[i] = i;
- _rank[i] = 0;
- }
- }
- int find(int x) {
- if (parent[x] == x)
- return x;
- else {
- return parent[x] = find(parent[x]);
- }
- }
- void unite(int a, int b) {
- a = find(a);
- b = find(b);
- if (a == b) return;
- if (_rank[a] < _rank[b]) {
- parent[b] = a;
- }
- else {
- parent[a] = b;
- if (_rank[a] == _rank[b]) {
- _rank[a]++;
- }
- }
- }
- int main(void)
- {
- cin >> N >> M;
- ll ans = 0;
- init();
- for (int i = 1; i <= N; i++)
- scanf(" %c ", &univ[i]);
- for (int i = 0; i < M; i++) {
- int u, v, c;
- cin >> u >> v >> c;
- if (univ[u] != univ[v]) {
- G.push(route(u, v, c));
- }
- }
- while (!G.empty()) {
- int u = G.top().u, v = G.top().v, c = G.top().cost;
- G.pop();
- if (find(u) != find(v)) {
- unite(u, v);
- vi[u] = true;
- vi[v] = true;
- ans += c;
- }
- }
- for (int i = 1; i <= N; i++) {
- if (vi[i] == false) {
- printf("-1\n");
- return 0;
- }
- }
- printf("%lld\n", ans);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement