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;
}
相关推荐
hsling松子1 小时前
使用PaddleHub智能生成,献上浓情国庆福
人工智能·算法·机器学习·语言模型·paddlepaddle
dengqingrui1232 小时前
【树形DP】AT_dp_p Independent Set 题解
c++·学习·算法·深度优先·图论·dp
C++忠实粉丝2 小时前
前缀和(8)_矩阵区域和
数据结构·c++·线性代数·算法·矩阵
ZZZ_O^O2 小时前
二分查找算法——寻找旋转排序数组中的最小值&点名
数据结构·c++·学习·算法·二叉树
CV-King3 小时前
opencv实战项目(三十):使用傅里叶变换进行图像边缘检测
人工智能·opencv·算法·计算机视觉
代码雕刻家3 小时前
数据结构-3.9.栈在递归中的应用
c语言·数据结构·算法
雨中rain3 小时前
算法 | 位运算(哈希思想)
算法
Kalika0-05 小时前
猴子吃桃-C语言
c语言·开发语言·数据结构·算法
sp_fyf_20245 小时前
计算机前沿技术-人工智能算法-大语言模型-最新研究进展-2024-10-02
人工智能·神经网络·算法·计算机视觉·语言模型·自然语言处理·数据挖掘
我是哈哈hh7 小时前
专题十_穷举vs暴搜vs深搜vs回溯vs剪枝_二叉树的深度优先搜索_算法专题详细总结
服务器·数据结构·c++·算法·机器学习·深度优先·剪枝