POJ 3613 Cow Relays(矩阵模板+快速幂+floyd)
程序员文章站
2022-07-04 20:06:49
...
题目地址
题意:给你一个图,要求你一定要经过K步从s到达t,求最短路为多少
思路:通过矩阵快速幂以及floyd的思想定义出一个矩阵,一个矩阵代表的是经过了n条边从i到达j,另一个矩阵代表的是经过了m条边从i到达j,则两个矩阵相乘代表的是经过了n+m条边从i到达j,这样就能求出来了。
在知乎看到了为什么floyd要把k放在最外层:
#include <iostream>
#include <cstring>
#include <string>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <cmath>
#include <cstdio>
#include <algorithm>
#include <iomanip>
#define N 210
#define LL __int64
#define inf 0x3f3f3f3f
#define lson l,mid,ans<<1
#define rson mid+1,r,ans<<1|1
#define getMid (l+r)>>1
#define movel ans<<1
#define mover ans<<1|1
using namespace std;
const LL mod = 1000000007;
int K, n, m, s, t;
struct Matrix {
int a[N][N];
Matrix operator * (Matrix &r) {
Matrix c;
memset(c.a, inf, sizeof(c.a));
for (int i = 1; i <= n; i++)//floyd不同的是把k放在内层了
for (int j = 1; j <= n; j++)
for (int k = 1; k <= n; k++)
c.a[i][j] = min(c.a[i][j], a[i][k] + r.a[k][j]);
return c;
}
}ans, cnt;
map<int, int> mapp;
void power() {
cnt = ans;
K--;
while (K) {
if (K & 1) ans = ans*cnt;
cnt = cnt * cnt;
K >>= 1;
}
}
int main() {
cin.sync_with_stdio(false);
int a, b, c;
while (cin >> K >> m >> s >> t) {
memset(ans.a, inf, sizeof(ans.a));
n = 0;
mapp.clear();
for (int i = 0; i < m; i++) {
cin >> c >> a >> b;
if (mapp.find(a) != mapp.end()) {
a = mapp[a];
}
else {
mapp[a] = ++n;
a = n;
}
if (mapp.find(b) != mapp.end()) {
b = mapp[b];
}
else {
mapp[b] = ++n;
b = n;
}
ans.a[a][b] = ans.a[b][a] = c;
}
power();
cout << ans.a[mapp[s]][mapp[t]] << endl;
}
return 0;
}
上一篇: 稀疏矩阵与压缩存储
下一篇: POJ 3176 Cow Bowling