编程练习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;
}
相关推荐
爱浦路 IPLOOK2 天前
从传统到轻量级5G:网络架构演变与优化路径
5g·核心网
柏颖漫谈2 天前
半数用户不用5G,将推动5G套餐降价,用低价吸引用户
5g
XLTYQYB3 天前
6121A 音频分析仪
5g
爱浦路 IPLOOK6 天前
轻量级5G核心网:适应未来网络需求的关键方案
网络·5g·核心网
ianvtenr7 天前
基于千兆5G网关的5G急救车方案
5g·5g网关·救护车
明朝百晓生7 天前
【无线感知会议系列-22 】Vivisecting Mobility Management in 5G Cellular Networks
5g
network_tester7 天前
5g基站测试要求和关键点
运维·网络·功能测试·网络协议·测试工具·5g·信息与通信
ianvtenr9 天前
基于微型5G网关的石化厂区巡检机器人应用
5g·机器人·巡检机器人
思茂信息10 天前
CST的TLM算法仿真5G毫米波阵列天线及手机
网络·人工智能·5g·智能手机·软件工程·软件构建
XLTYQYB10 天前
R&S®RTP 示波器
科技·5g