BZOJ 1614
Luogu 1948
from: USACO 2008 Jan Sliver(USACO刷题第18题)
如果去掉一条路径上的边,肯定要优先删掉大的边,所以我们可以二分整条路径上的第$k+1$大的边,把比他小边的设为0,大的设为1
然后最后的$dis[n]$就是如果第$k+1$大的边为当前二分$mid$值,所需要免费的边数,即可判断可行性。
注意:无向图的边数组要开多两倍!!!牢记!!!
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define ms(i, j) memset(i, j, sizeof i)
using namespace std;
const int MAXN = 1000 + 5, MAXM = 10000 + 5, INF = 1000000000;
struct edge{int v, wi;}e[MAXM*2]; //无向边要*2!
int en, n, m, k;
vector<int> G[MAXN];
void ins(int u, int v, int wi) {
en++, e[en].v = v, e[en].wi = wi, G[u].push_back(en);
en++, e[en].v = u, e[en].wi = wi, G[v].push_back(en);
}
void clean() {
for (int i=0;i<=n;i++) G[i].clear();
en = 0;
}
void init() {
clean();
for (int i=1;i<=m;i++) {
int ai, bi, li; scanf("%d%d%d", &ai, &bi, &li);
ins(ai, bi, li);
}
}
int dis[MAXN], vi[MAXN];
bool check(int x) {
queue<int> q;
for (int i=1;i<=n;i++) dis[i] = INF, vi[i] = false;
dis[1] = 0, q.push(1), vi[1] = true;
while (!q.empty()) {
int u = q.front(); q.pop(); vi[u] = false;
for (int i=0;i<G[u].size();i++) {
edge p = e[G[u][i]];
int v = p.v, w = p.wi;
if (dis[v]>dis[u]+(p.wi>x)) {
dis[v] = dis[u]+(p.wi>x);
if (!vi[v]) q.push(v), vi[v] = true;
}
}
}
return dis[n]<=k;
}
void solve() {
int ans = -1, l = 0, r = 1000005;
while (l<r) {
int mid = (l+r)>>1;
if (check(mid)) {
ans = mid;
r = mid;
} else l = mid + 1;
}
printf("%d\n", ans);
}
int main() {
#ifndef ONLINE_JUDGE
freopen("1.in", "r", stdin);freopen("1.out", "w", stdout);
#endif
while (scanf("%d%d%d", &n, &m, &k)==3) init(), solve();
return 0;
}