编程练习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;
}
相关推荐
写代码写到手抽筋6 天前
通信基站相关学习链接
学习·5g
沐欣工作室_lvyiyi8 天前
基于5G的车辆跟驰预警系统(论文+源码)
stm32·单片机·5g·毕业设计
AIMarketing10 天前
飞猫M505G网速技术解析峰值1.6Gbps技术原理
运维·服务器·5g
摩拜芯城IC13 天前
PSD835G2-90UI 芯片参数资料意法半导体Flash PSD可编程系统微芯片
python·5g
PuEJbfWWgo14 天前
S7-1500在洁净空调控制系统中的实战应用
5g
x-cmd16 天前
[x-cmd] Gemma 3 家族新成员:T5Gemma 2 正式发布,重新定义紧凑型编解码模型的性能上限
5g·google·x-cmd·gemma
无忧智库17 天前
低空经济新基建:5G-A通感一体化智联网如何重塑万亿级低空市场格局(WORD)
5g
之歆18 天前
RAID 磁盘阵列与 LVM 逻辑卷管理
运维·5g
安科士andxe18 天前
实操指南|安科士1.25G CWDM SFP光模块选型、部署与运维全攻略
运维·数据库·5g
modem协议笔记19 天前
3GPP R19 中redcap支持PC 2
网络·5g·智能手机