欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > 编程练习7 5G网络建设

编程练习7 5G网络建设

2025/2/24 12:26:04 来源:https://blog.csdn.net/lucky_greenegg/article/details/142963800  浏览:    关键词:编程练习7 5G网络建设

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

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

#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;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词