题目大意
给定有n个点,m条边的无向图
你要从1号点走到n号点,在此过程中,你可以忽略k次路程的距离(可以比k小)
问剩下路程中最长路段的最小值是多少
解法
最大值最小,显然可以用二分套最短路解决,但是这里我们基于dp思想,用一个dp数组记录在某个节点 i 忽略 j 次后所得到的最小的最大值
代码如下:
#include <bits/stdc++.h>
using namespace std;
const int M = 200010;
const int N = 1010;
struct node1
{
int to, next;
int dist;
};
int dist[N][N];
struct node2
{
int to, level;
bool friend operator<(node2 a, node2 b)
{
return dist[a.to][a.level] > dist[b.to][b.level];
}
};
bool vis[N][N];
int n, m, k, cnt;
int head[N];
node1 edge[M];
void add(int come, int to, int val)
{
cnt++;
edge[cnt].next = head[come];
edge[cnt].to = to;
edge[cnt].dist = val;
head[come] = cnt;
}
void spfa() // 1-->n
{
priority_queue<node2> q;
q.push(node2{1, 0});
vis[1][0] = true;
dist[1][0] = 0;
while (!q.empty())
{
int u = q.top().to;
int l = q.top().level;
q.pop();
vis[u][l] = false;
for (int i = head[u]; i; i = edge[i].next)
{
int v = edge[i].to;
//printf("%d->%d\n", u, v);
if (dist[v][l] > max(dist[u][l], edge[i].dist))
{
dist[v][l] = max(dist[u][l], edge[i].dist);
if (vis[v][l] == false)
{
q.push(node2{v, l});
vis[v][l] = true;
}
}
if (min(edge[i].dist, dist[v][l + 1]) > dist[u][l] && l < k)
{
dist[v][l + 1] = dist[u][l];
if (vis[v][l + 1] == false)
{
q.push(node2{v, l + 1});
vis[v][l + 1] = true;
}
}
}
}
}
int main()
{
scanf("%d%d%d", &n, &m, &k);
for (int i = 1, u, v, w; i <= m; i++)
{
scanf("%d%d%d", &u, &v, &w);
add(u, v, w);
add(v, u, w);
}
memset(dist, 0x7f, sizeof(dist));
spfa();
int ans = 0x7f7f7f7f;
for (int i = 0; i <= k; i++)
ans = min(ans, dist[n][i]);
printf("%d", (ans!=0x7f7f7f7f)?(ans):(-1));
return 0;
}
/*
5 7 0
1 2 5
3 1 4
2 4 8
3 2 3
5 2 9
3 4 7
4 5 6
2 2 2
1 1 1
1 2 1
*/