[第15次CCFCSP]数据中心

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=1e5+5;
int cnt=0,ans=0;
int head[N];
int n,m,root;
int maxx=-1;
struct node
{
	int u;
	int v;
	int w;
}edge[N];

int father[N];
void init()
{
	for(int i=1;i<=N;i++)
	{
		father[i]=i;
	}
}
int find_set(int n)
{
	return father[n]==n?n:(father[n]=find_set(father[n]));
}
void union_set(int a,int b)
{
	int x=find_set(a);
	int y=find_set(b);
	if(a!=b)
	{
		father[b]=a;
	}
}
bool cmp(node a,node b)
{
	return a.w<b.w;
}
void kruskal()
{
	sort(edge+1,edge+1+m,cmp);
	for(int i=1;i<=m;i++)
	{
		if(cnt==n-1)break;
		int a=find_set(edge[i].u);
		int b=find_set(edge[i].v);
		if(a==b)continue;
		else
		{
			father[b]=a;
			cnt++;
			ans+=edge[i].w;
			maxx=max(maxx,edge[i].w);
		} 
	}
}
int main()
{
	cin>>n>>m>>root;
	for(int i=1;i<=m;i++)
	{
		int u,v,w;
		cin>>edge[i].u>>edge[i].v>>edge[i].w;
	}
	init();
	kruskal();
	cout<<maxx;
	return 0;
}

通过kruskal算法求出最短路,在把符合条件的边加入总值时每次比较maxx更新最大值,输出即可。

模板题

相关推荐
exm-zem11 分钟前
多用户图书管理系统
c++
☆璇13 分钟前
【数据结构】排序
c语言·开发语言·数据结构·算法·排序算法
我要成为c嘎嘎大王13 分钟前
【C++】初识C++(1)
开发语言·c++
艾莉丝努力练剑3 小时前
【LeetCode&数据结构】单链表的应用——反转链表问题、链表的中间节点问题详解
c语言·开发语言·数据结构·学习·算法·leetcode·链表
_殊途5 小时前
《Java HashMap底层原理全解析(源码+性能+面试)》
java·数据结构·算法
还债大湿兄5 小时前
《C++内存泄漏8大战场:Qt/MFC实战详解 + 面试高频陷阱破解》
c++·qt·mfc
珊瑚里的鱼8 小时前
LeetCode 692题解 | 前K个高频单词
开发语言·c++·算法·leetcode·职场和发展·学习方法
AI+程序员在路上8 小时前
QTextCodec的功能及其在Qt5及Qt6中的演变
开发语言·c++·qt
Risehuxyc8 小时前
C++卸载了会影响电脑正常使用吗?解析C++运行库的作用与卸载后果
开发语言·c++
秋说9 小时前
【PTA数据结构 | C语言版】顺序队列的3个操作
c语言·数据结构·算法