快速幂+最短路+DP
Code:
#include<bits/stdc++.h>
using namespace std;
const int N = 210,M=110,INF=0x3f3f3f3f;
int n, m;
int g[N][N],res[N][N];//初始时g表示的是只有一条边时的最短边数组
int s, e, k;
map<int, int> ids;
int cnt = 0;
void mul(int a[][N], int b[][N], int c[][N]) {
static int tmp[N][N],tmp2[N][N];
memcpy(tmp, b, sizeof tmp);
memcpy(tmp2, c, sizeof tmp2);
memset(a, 0x3f, sizeof tmp);
for (int k = 1; k <= cnt; k++) {
for(int i=1;i<=cnt;i++)
for (int j = 1; j <= cnt; j++) {
a[i][j] = min(a[i][j], tmp[i][k] + tmp2[k][j]);
}
}
}
void qmi() {
memset(res, 0x3f, sizeof res);
for (int i = 1; i <= cnt; i++)res[i][i] = 0;
while (k) {
if (k & 1)mul(res, res, g);
mul(g, g, g);
k >>= 1;
}
}
int main() {
cin >> k >> m >> s >> e;
memset(g, 0x3f, sizeof g);
for (int i = 1; i <= m; i++) {
int a, b, c;
cin >> c >> a >> b;
if (!ids.count(a))ids[a] = ++cnt;
a = ids[a];
if (!ids.count(b))ids[b] = ++cnt ;
b = ids[b];
g[a][b] = g[b][a] = min(g[a][b], c);
}
s = ids[s], e = ids[e];
qmi();
cout << res[s][e] << endl;
}
这里要特别注意res数组和g数组的初始化,res表示的是经过0条边时的最短路数组,所以除了从i->i外都是INF,g表示的是经过1条边时的最短路数组,所以不需要把g[i][i]标记为0,即:一个点不可能只经过一条边到达自己,在没有自环的情况下