编程练习7 5G网络建设

需要用到并查集的相关知识:可以参考如下链接

并查集详解(原理+代码实现+应用+优化)-CSDN博客

cpp 复制代码
#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;
 
vector<int> split(string params_str) {
    vector<int> p;
    while (params_str.find(" ") != string::npos) {
        int found = params_str.find(" ");
        p.push_back(stoi(params_str.substr(0, found)));
        params_str = params_str.substr(found + 1);
    }    
    p.push_back(stoi(params_str));
    return p;
}
 
vector<string> split_str(string params_str) {
    vector<string> p;
    while (params_str.find(" ") != string::npos) {
        int found = params_str.find(" ");
        p.push_back(params_str.substr(0, found));
        params_str = params_str.substr(found + 1);
    }    
    p.push_back(params_str);
    return p;
}  
 
// 并查集实现
class UnionFind{
    vector<int> root;
    vector<int> rank;
    int cnt;
 
public:
// 初始化数据结构
    UnionFind(int N) : cnt(0){
        root.resize(N+1);
        rank.reserve(N+1);
        for (int i = 0; i < N+1; ++i) {
            root[i] = i;
            rank[i] = 1;
        }
    }
 
    int find(int x) {
        if (x == root[x]) {
            return x;
        }
        return root[x] = find(root[x]);
    }
 
    void union_op(int x, int y) {
        root[find(x)] = find(y);
        cnt+=1;
    }
 
    int get_count(){
        return cnt;
    }
};
 
 
int main()
{
 
    int n,m;
    cin >> n >> m;
    UnionFind uf(n);
 
    vector<vector<int>> networks;
    for (int i = 0; i < m; i++) {
        int a,b,c,d;
        cin >> a >> b >> c >> d;
        if (d == 1) {
            if (uf.find(a) != uf.find(b)) {
                uf.union_op(a, b);
            }
        } else {
            networks.push_back(vector<int>{a,b,c});
        }
    }
    sort(networks.begin(), networks.end(),[](vector<int> a ,vector<int> b){
		return a[2]<b[2];
	});
 
 
    int result = 0;
    int i=0;
    while(true){
        if(i>=networks.size()){
            break;
        } else {
            if (uf.find(networks[i][0]) != uf.find(networks[i][1])) {
                uf.union_op(networks[i][0], networks[i][1]);
                result += networks[i][2];
                if (uf.get_count() == n - 1) {
                    break;
                }
            }
        }
        i+=1;
    }
 
    if(uf.get_count() != n - 1){
        result = -1; 
    }
    cout<<result<<endl;
    return 0;
}
相关推荐
寺中人18 分钟前
基于 5G 物联网的智慧养老全方位安全监测系统
人工智能·物联网·5g·安全·智能家居
CableTech_SQH14 小时前
华中科技大学同济医学院附属协和医院重庆医院智能化建设 F5G 全光方案百盛分析报告
大数据·网络·5g·运维开发·信息与通信
2zcode19 小时前
基于MATLAB的5G物理层文本传输系统仿真与性能分析
开发语言·5g·matlab
木心术119 小时前
基于FPGA+RFIC的5G基站设计方案与5G专用DFE芯片的设计方案区别及优劣势分析
5g·fpga开发
写代码写到手抽筋1 天前
5G DMRS 功率 Boost 与幅度缩放
5g
龙亘川1 天前
智慧高速新底座:F5G 全光通信网架构、关键技术与场景落地实践
5g·架构
xwz小王子1 天前
Nature Sensor 揭示触觉/嗅觉/味觉如何通过5G/6G实现远程真实传递
5g
xiaoxiaoxiaolll2 天前
《Light》新论文:335GHz太赫兹通信如何跨越2.2公里?
5g
疯狂成瘾者3 天前
5G 定位
5g
CableTech_SQH4 天前
F5G 全光网,赋能智慧校园数字化建设
大数据·网络·5g·运维开发·信息与通信