[第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更新最大值,输出即可。

模板题

相关推荐
sheeta199820 分钟前
LeetCode 每日一题笔记 日期:2026.06.06 题目:2196. 根据描述创建二叉树
笔记·算法·leetcode
小欣加油28 分钟前
leetcode994 腐烂的橘子
数据结构·c++·算法·leetcode·bfs
.千余1 小时前
【C++】手写双向链表:list容器模拟实现
开发语言·c++·笔记·学习·其他
QuZero1 小时前
Guava Cache Deep Dive
java·后端·算法·guava
随意起个昵称1 小时前
线性dp-LIS题目4(A Twisty Movement)
算法·动态规划
liulilittle2 小时前
过冲:拥塞控制的呼吸与盲行
linux·网络·c++·tcp/ip·计算机网络·tcp·通信
Felven2 小时前
B. Fair Numbers
数据结构·算法
人道领域2 小时前
【LeetCode刷题日记】93.复原IP地址
java·开发语言·算法·leetcode
jarreyer2 小时前
【算法记录1】模型训练问题
算法
Felven2 小时前
D. Friends and the Restaurant
算法