第一种解法是分层图,空间开销实在太大了,记录第二个解法。
分层图解法请参考 https://blog.csdn.net/weixin_43701790/article/details/105025547
题目链接 http://poj.org/problem?id=3662
其实这个题目可以二分求解的。可以很清晰的发现,本题的结果具有单调性,对于一个更小的结果而言,比它大的一定符合条件。根据单调性进行二分,二分最后的花销,对于边的长度大于mid(也就是需要免费的边)的边,将其置为1,其余的为0,跑1到n的单源最短路,最后的 dist[n] 就是免费边的个数,与k进行比较,继续二分即可。
/**
* Author : correct
*/
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <queue>
using namespace std;
#define mem(a, b) memset(a, b, sizeof a)
#define INF 0x3f3f3f3f
const int N = 201000, M = 1010;
int head[M], nex[N * 2], to[N * 2], ed[N * 2];
int cnt;
int n, m, k;
void add(int a, int b, int c){
++cnt;
ed[cnt] = c;
to[cnt] = b;
nex[cnt] = head[a];
head[a] = cnt;
}
bool vis[M];
int d[M];
bool check(int mid){
queue<int > q;
mem(d, 0x3f);
mem(vis, 0);
q.push(1);
d[1] = 0;
vis[1] = 1;
while (!q.empty()){
int t = q.front();
q.pop();
vis[t] = 0;
for (int i = head[t]; i; i = nex[i]){
int y = to[i];
int c = ed[i];
int dist = 0x3f3f3f3f;
if (c > mid){
dist = 1;
}
else dist = 0;
if (d[y] > d[t] + dist){
d[y] = d[t] + dist;
if (vis[y] == 0){
q.push(y);
vis[y] = 1;
}
}
}
}
return d[n] <= k;
}
int main()
{
cnt = 0;
ios::sync_with_stdio(false);
cin >> n >> m >> k;
int l = 0;
int r = -1;
for (int i = 0; i < m; i++){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
add(b, a, c);
r = max(r, c);
}
int ans = 0x3f3f3f3f;
while (l < r){
int mid = (l + r) >> 1;
if (check(mid)){
r = mid;
ans = mid;
}
else l = mid + 1;
}
cout << (ans == INF ? -1 : ans) << "\n";
return 0;
}