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 均不相同
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include

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>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) {
	queueq;
	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;
}

你可能感兴趣的:(最小生成树,最短路,图论,算法)