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;
}
相关推荐
倒头就睡的小比特3 小时前
算法竞赛C++常用的STL
c++·算法
小羊没烦恼!3 小时前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
猎头南楼4 小时前
知识社区推荐系统实践:新用户冷启动与长短期兴趣建模的挑战 资深推荐算法工程师
人工智能·深度学习·算法·机器学习
旖旎夜光5 小时前
力控面试题 01.01: 判定字符是否唯一(位运算) —— 题解
c++·学习·算法·leetcode·力控
wzdark5 小时前
大规模并行计算中的负载均衡算法研究4
算法
Because_of_Her15 小时前
并查集-听课笔记
笔记·算法·并查集
码流子6 小时前
高速公路安全监测实践:碰撞监测预警+物联网底座,从感知到处置的闭环
大数据·人工智能·物联网·算法·架构
another heaven6 小时前
【算法/C++ MD5算法能否逆解码?原理、C++实现与同类哈希算法对比】
c++·算法·哈希算法
wzdark6 小时前
从算法设计模式看编程思维的抽象能力4
算法
2601_962218616 小时前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法