AcWing 178. 第K短路
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/53ec7e51b0af7257965d35906f0af687.png)
Code
int n, m, S, T, k;
vector<int> a[1003][1003], b[1003][1003];
int vis[1003], f[1004];
void dfs()
{
priority_queue<pii, vector<pii>, greater<pii> > q;
mt(f, 0x3f); mt(vis, 0);
f[T] = 0;
q.push({ 0, T });
while (sz(q))
{
int x = q.top().sd; q.pop();
if (vis[x]) continue;
vis[x] = 1;
for (int y = 1; y <= n; y++)
for (auto w : b[x][y])
if (f[y] > f[x] + w)
f[y] = f[x] + w,
q.push({ f[y], y });
}
}
#define piii pair<int, pair<int, int> >
int d[1003];
int A()
{
priority_queue<piii, vector<piii>, greater<piii> > q;
mt(vis, 0);
q.push({ f[S], {0 , S} });
while (sz(q))
{
int ans = q.top().sd.ft;
int x = q.top().sd.sd;
q.pop();
if (vis[x] > k) continue;
vis[x]++;
if (vis[T] == k) { return ans; }
for (int y = 1; y <= n; y++)
if (vis[y] < k)
for (auto w : a[x][y])
d[y] = ans + w,
q.push({ ans + f[y] + w, { ans + w, y} });
}
return -1;
}
int main()
{
IOS;
cin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, z; cin >> x >> y >> z;
a[x][y].push_back(z);
b[y][x].push_back(z);
}
cin >> S >> T >> k;
if (!m)
{
cout << -1 << endl;
return 0;
}
dfs();
if (S == T) k++;
cout << A() << endl;
return 0;
}