# poj-2449-Remmarguts' Date(A*算法+Dijkstra)

#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <cmath>
#include <queue>
#include <vector>
#include <algorithm>
#define ll long long
using namespace std;
const int inf = 0x3fffffff;
const int MAXN = 1003;
const int MAXM = 100005;
int n, m;
struct Edge{
int u, v, w;
} edge[MAXM];
int head[MAXN], to[MAXM], next[MAXM], length[MAXM], tot;
int dist[MAXN];
bool vis[MAXN];
priority_queue<pair<int, int> > heap;

void init() {
tot = 0;
}

void addEdge(int u, int v, int w) {
to[tot] = v;
length[tot] = w;
}

bool dijkstra(int s, int t) {
for (int i = 0; i <= n; i++) {
dist[i] = inf;
vis[i] = false;
}
dist[s] = 0;
for (int i = 1; i <= n; i++) {
int Min = inf;
int v = -1;
for (int j = 1; j <= n; j++) {
if (!vis[j] && Min > dist[j]) {
Min = dist[j];
v = j;
}
}
if (v == -1) {
break;
}
vis[v] = true;
for (int j = head[v]; j != -1; j = next[j]) {
if (!vis[to[j]] && dist[to[j]] > dist[v] + length[j]) {
dist[to[j]] = dist[v] + length[j];
}
}
}
return dist[t] != inf;
}

int solve(int a, int b, int k) {
init();
for (int i = 0; i < m; i++) {
//建图的时候把边都变成反向边
}
if (!dijkstra(b, a)) {
//dijkstra算法求的是从b到a的最短路
return -1;
}
init();
for (int i = 0; i < m; i++) {
// 这时候再把边变成正向边
}
while(!heap.empty()) {
heap.pop();
}
heap.push(pair<int, int>(-dist[a], a));
// heap里 第一个数是从第二个数到b的距离的负值
// heap会先按照第一个int降序排列，第一个相等的就按照第二个int降序排列
// 为了是最近的放在第一个位置，就把距离变成负值
while(!heap.empty()) {
pair<int, int> ret = heap.top();
heap.pop();
int real = -ret.first - dist[ret.second];
// real是从a到ret.second 的真正距离
if (ret.second == b) {
if (!--k) {
return real;
}
}
for (int i = head[ret.second]; i != -1; i = next[i]) {
heap.push(pair<int, int>(-(real + length[i] + dist[to[i]]), to[i]));
// 放到heap的是从a到ret.second再到to[i]再到b的最短距离的负值
}
}
return -1;
}

int main()
{
#ifndef ONLINE_JUDGE
freopen("1.txt", "r", stdin);
#endif
int a, b, k, i, j;
while(cin >> n >> m) {
for (i = 0; i < m; i++) {
scanf("%d%d%d", &edge[i].u, &edge[i].v, &edge[i].w);
}
scanf("%d%d%d", &a, &b, &k);
if (a == b) {
// a和b相等的时候k一定要加1
k++;
}
cout << solve(a, b, k) << endl;
}
return 0;
}


©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客