POJ3613 Cow Relays(矩阵乘法floyd+快速幂)

本文介绍了一种使用矩阵快速幂求解无向连通图中从节点S到节点E经过k条边的最短路径的方法。通过预处理矩阵并运用快速幂技巧,可以高效地解决此类问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:给出一张无向连通图,求S到E经过k条边的最短路。

分析:居然和矩阵快速幂联系起来了,详见《算法竞赛进阶指南》P363。

代码:

#include <map>
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 206, INF = 0x3f3f3f3f;
int n, t, s, e, tot = 200;
map<int, int> m;
struct M {
	int a[N][N];
	void pre() {
		for (int i = 1; i <= tot; i++)
			for (int j = 1; j <= tot; j++)
				a[i][j] = INF;
	}
} st, ed;

M mul(M a, M b) {
	M c;
	c.pre();
	for (int i = 1; i <= tot; i++)
		for (int j = 1; j <= tot; j++)
			for (int k = 1; k <= tot; k++)
				c.a[i][j] = min(c.a[i][j], a.a[i][k] + b.a[k][j]);
	return c;
}

int main() {
	cin >> n >> t >> s >> e;
	st.pre();
	tot = 0;
	while (t--) {
		int x, y, z;
		scanf("%d %d %d", &z, &x, &y);
		x = m[x] ? m[x] : (m[x] = ++tot);
		y = m[y] ? m[y] : (m[y] = ++tot);
		st.a[x][y] = st.a[y][x] = z;
	}
	memcpy(ed.a, st.a, sizeof(ed.a));
	--n;
	while (n) {
		if (n & 1) ed = mul(ed, st);
		st = mul(st, st);
		n >>= 1;
	}
	cout << ed.a[m[s]][m[e]] << endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值