• noi.ac #39 MST


    MST 模板题

    #include <iostream>
    #include <cstdio>
    #include <algorithm>
    #include <cmath>
    #include <cstring>
    #include <string>
    
    using namespace std;
    const int N = 5e5 + 10;
    
    #define LL long long
    #define gc getchar()
    #define Rep(i, a, b) for(int i = a; i <= b; i ++)
    
    inline int read() {
    	int x = 0;
    	char c = gc;
    	while(c < '0' || c > '9') c = gc;
    	while(c >= '0' && c <= '9') x = x * 10 + c - '0', c = gc;
    	return x;
    }
    
    struct Node {
    	int u, v, w;
    	bool operator < (const Node a) const {
    		return this-> w > a.w;
    	}
    } E[N];
    int fa[N];
    LL Answer, tot;
    int n, m;
    
    int Get(int x) {
    	return fa[x] == x ? x : fa[x] = Get(fa[x]);
    }
    
    void Kruskal() {
    	int js = 0;
    	Rep(i, 1, m) {
    		int u = E[i].u, v = E[i].v, fau = Get(u), fav = Get(v);
    		if(fau != fav) {
    			fa[fau] = fav;
    			Answer += E[i].w;
    			js ++;
    		}
    		if(js == n - 1) return ;
    	}
    }
    
    int main() {
    	n = read(), m = read();
    	Rep(i, 1, m) {
    		E[i] = (Node) {
    			read(), read(), read()
    		};
    		tot += E[i].w;
    	}
    	Rep(i, 1, n) fa[i] = i;
    	sort(E + 1, E + m + 1);
    	Kruskal();
    	cout << tot - Answer;
    	return 0;
    }
    
  • 相关阅读:
    linux 常用命令
    restframeword之视图,解析器
    restframework之序列化
    restframeword之APIview
    MongoDB
    redis
    mysql优化
    (java)图片像素的操作
    关于java AudioInputStream播放短音频没声音的问题
    java向文件中追加内容的一种简单方式
  • 原文地址:https://www.cnblogs.com/shandongs1/p/9720291.html
Copyright © 2020-2023  润新知