题目:178. 第K短路
分析:模板
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define print(i) cout << "debug: " << i << endsl
#define close() ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
#define mem(a, b) memset(a, b, sizeof(a))
#define pb(a) push_back(a)
#define x first
#define y second
typedef pair<int, int> pii;
const ll mod = 1e9 + 7;
const int maxn = 1e5 + 10;
const int inf = 0x3f3f3f3f;
struct edge
{
int v, val, nex;
}e[maxn << 1];
struct node
{
int dis, nowdis, u;
bool operator< (const node b) const{
return b.dis < dis;
}
};
int head1[maxn], head2[maxn], tot;
int s, t, k;
int n, m;
int dis[maxn], vis[maxn];
int cnt[maxn];
void init()
{
mem(head1, -1), mem(head2, -1), tot = 0;
}
void addedge(int head[], int x, int y, int val)
{
e[tot] = {y, val, head[x]};
head[x] = tot++;
}
void dj()
{
mem(dis, inf), dis[t] = 0;
priority_queue<pii, vector<pii>, greater<pii> > q; q.push({0, t});
while(!q.empty())
{
pii now = q.top(); q.pop();
int u = now.y;
if(vis[u]) continue;
vis[u] = 1;
for(int i = head2[u]; ~i; i = e[i].nex)
{
int v = e[i].v;
if(dis[v] > dis[u] + e[i].val)
dis[v] = dis[u] + e[i].val, q.push({dis[v], v});
}
}
}
int a_star()
{
priority_queue<node> q; q.push({dis[s], 0, s});
while(!q.empty())
{
node now = q.top(); q.pop();
int distance = now.dis, nowdis = now.nowdis, u = now.u;
cnt[u]++;
if(cnt[t] == k) return nowdis;
for(int i = head1[u]; ~i; i = e[i].nex)
{
int v = e[i].v;
if(cnt[v] < k)
q.push({nowdis + e[i].val + dis[v], nowdis + e[i].val, v});
}
}
return -1;
}
int main()
{
cin >> n >> m;
init();
for(int i = 1; i <= m; i++)
{
int a, b, c; cin >> a >> b >> c;
addedge(head1, a, b, c);
addedge(head2, b, a, c);
}
cin >> s >> t >> k;
if(t == s) k++;
dj();
cout << a_star() << endl;
}