题目大意:就是给出一个图,然后给出一个起点个一个终点,求这两点间的第K短路。本题中是可以走重复的路的,所以如果一张图中有一个环的话,无论求第几短路都是存在的。
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int MAXN = 1000;
const int MAXM = 100000;
struct node
{
int v, w;
node *next;
} Edges[MAXM*2+10], *ecnt = Edges, *adj[MAXN+10], *adj1[MAXN+10];
struct State
{
int f, id;
bool operator<(const State& s) const
{
return f>s.f;
}
};
priority_queue<State> que;
void addedge(int u, int v, int w)
{
++ecnt;
ecnt->v = v;
ecnt->w = w;
ecnt->next = adj[u];
adj[u] = ecnt;
}
void _addedge(int u, int v, int w)
{
++ecnt;
ecnt->v = v;
ecnt->w = w;
ecnt->next = adj1[u];
adj1[u] = ecnt;
}
int dis[MAXN+10];
bool inque[MAXN+10];
void SPFA(int res)
{
queue<int> que;
que.push(res);
inque[res] = true;
memset(dis, 0x3f, sizeof dis);
dis[res] = 0;
while(!que.empty())
{
res = que.front();
que.pop();
inque[res] = false;
for(node *p=adj1[res]; p; p=p->next)
{
int v=p->v;
if(dis[v] > dis[res] + p->w)
{
dis[v] = dis[res] + p->w;
if(!inque[v])
{
inque[v] = true;
que.push(v);
}
}
}
}
}
int main()
{
int n, m;
int S, T, K, u, v, w;
scanf("%d%d", &n, &m);
for(int i=1; i<=m; i++)
{
scanf("%d%d%d", &u, &v, &w);
addedge(u, v, w);
_addedge(v, u, w);
}
scanf("%d%d%d", &S, &T, &K);
if(S == T) K++;
SPFA(T);
State t1, t2;
t1.f = dis[S];
t1.id = S;
que.push(t1);
int counter = 0;
while(!que.empty())
{
t1 = que.top();
que.pop();
if(t1.id == T)
{
counter++;
if(counter == K)
{
printf("%d\n" ,t1.f);
return 0;
}
}
for(node *p=adj[t1.id]; p; p=p->next)
{
int v = p->v;
t2.f = t1.f - dis[t1.id] + p->w + dis[v];
t2.id = v;
que.push(t2);
}
}
printf("-1\n");
return 0;
}