Kruskal,最短路综合应用,一道图论一

Problem - 1525 (nefu.edu.cn)

Problem:1525

Time Limit:1000ms

Memory Limit:131072K

Description

复制代码
给定一个包含 n  个节点和 m  条边的图,每条边有一个权值。
你的任务是回答 k 个询问,每个询问包含两个正整数 s  和 t 表示起点和终点,要求寻找从 s 到 t  的一条路径,使得路径上权值最大的一条边权值最小。

Input

复制代码
第一行包含三个整数 n 、m 、k ,分别表示 n 个节点, m  条路径, k  个询问。

接下来 m  行,每行三个整数 u , v  , w, 表示一个由 u 到 v  的长度为 w  的双向边。

再接下来 k  行,每行两个整数 s  , t,表示询问从 s 连接到 t  的所有路径中单边长度最大值的最小值。

Output

复制代码
输出包含 k  行,每一行包含一个整数 p 。p  表示 s  连接到 t 的所有路径中单边长度最大值的最小值。另外,如果 s 到 t  没有路径相连通,输出 -1 即可。

Sample Input

复制代码
8 11 3
1 2 10
2 5 50
3 4 60
7 5 60
3 6 30
1 5 30
6 7 20
1 7 70
2 3 20
3 5 40
2 6 90
1 7
2 8
6 2

Sample Output

复制代码
30
-1
30

Hint

复制代码
对于 100% 的数据 n≤1000,m≤100000,k≤1000,w≤10000000  
本题可能会有重边。
为了避免 Special Judge,本题所有的 w 均不相同
cpp 复制代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<math.h>
#include<map>

using namespace std;
typedef long long LL;
const int N = 1e3 + 5, M = 1e5 + 5;
int n, m, k;
struct edge {
	int a, b, w;
}edge[M];
int fa[N],d[N],vis[N];
vector<pair<int, int>>G[N];

int find(int x) {
	if (fa[x] == x)
		return x;
	return fa[x] = find(fa[x]);
}

int cmp(const struct edge& a, const struct edge& b) {
	return a.w < b.w;
}

void spfa(int x) {
	queue<int>q;
	memset(d, 0x3f3f3f3f, sizeof(d));
	memset(vis, 0, sizeof(vis));
	d[x] = 0;
	q.push(x);
	int t;
	while (!q.empty()) {
		t = q.front();
		q.pop();
		vis[x] = 0;
		for (int i = 0,j,w; i < G[t].size(); i++) {
			j = G[t][i].first, w = G[t][i].second;
			if (d[j] > max(d[t],w)) {
				d[j] = max(d[t], w);
				if (!vis[j]) {
					q.push(j);
					vis[j] = 1;
				}
			}
		}
	}
}

int main() {
	scanf("%d%d%d", &n, &m, &k);
	for (int i = 1; i <= m; i++) {
		scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].w);
	}
	for (int i = 1; i <= n; i++) {
		fa[i] = i;
	}
	sort(edge + 1, edge + 1 + m, cmp);
	int x, y;
	for (int i = 1; i <= m; i++) {
		x = find(edge[i].a);
		y = find(edge[i].b);
		if (y != x) {
			G[edge[i].a].push_back({ edge[i].b,edge[i].w });
			G[edge[i].b].push_back({ edge[i].a,edge[i].w });
			fa[x] = y;
		}
	}
	for (int i = 1; i <= k; i++) {
		scanf("%d%d", &y, &x);
		spfa(y);
		if (d[x] == 0x3f3f3f3f)
			printf("-1\n");
		else {
			printf("%d\n", d[x]);
		}
	}

	return 0;
}
相关推荐
2401_891482172 小时前
多平台UI框架C++开发
开发语言·c++·算法
88号技师3 小时前
2026年3月中科院一区SCI-贝塞尔曲线优化算法Bezier curve-based optimization-附Matlab免费代码
开发语言·算法·matlab·优化算法
t198751283 小时前
三维点云最小二乘拟合MATLAB程序
开发语言·算法·matlab
x_xbx3 小时前
LeetCode:148. 排序链表
算法·leetcode·链表
Darkwanderor3 小时前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_831920744 小时前
分布式系统安全通信
开发语言·c++·算法
WolfGang0073214 小时前
代码随想录算法训练营 Day17 | 二叉树 part07
算法
温九味闻醉4 小时前
关于腾讯广告算法大赛2025项目分析1 - dataset.py
人工智能·算法·机器学习
炽烈小老头4 小时前
【 每天学习一点算法 2026/03/23】数组中的第K个最大元素
学习·算法·排序算法
老鱼说AI4 小时前
大规模并发处理器程序设计(PMPP)讲解(CUDA架构):第四期:计算架构与调度
c语言·深度学习·算法·架构·cuda