编程练习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;
}
相关推荐
WHS-_-20229 小时前
Testbed Development: An Intelligent O-RAN-Based Cell-Free MIMO Network
5g
孟先生丨2 天前
PVE 系统 2.5G网卡驱动从 r8169 切换到 r8125
服务器·5g
GY68663 天前
多功能、高算力5G车载通信模组 MF572E-BC
5g
YUANQIANG20243 天前
5G与6G通信技术对比分析
5g·信息与通信
赋能大师兄5 天前
5G技术概述与未来演进
5g·6g
赋能大师兄6 天前
5G业务解决方案与典型行业应用
5g·解决方案·行业应用
龙亘川6 天前
5G+智慧文旅:技术驱动下的产业变革与体验升级(附白皮书解读)
5g·数字化转型·智慧文旅·vrar·产业互联网·白皮书解读·中国智造
2501_941403768 天前
5G技术与未来通信:赋能智慧城市与万物互联
人工智能·5g·智慧城市
爱浦路 IPLOOK8 天前
打造智慧校园:5G高校实验室建设的五大关键环节
5g
2501_941142139 天前
边缘计算与5G结合在智慧交通信号优化与实时路况预测中的创新应用
人工智能·5g·边缘计算