题意
有c个城市和r条道路,每条道路有一个为h的高度限制(h==-1时无高度限制)和长度len,给出起点城市到终点城市,在满足每条道路的高度限制时,求最大化运输高度时的最短路径长度。
思路
先用二分求出最大的可行高度,然后用spfa对每一个值运行,如果能够走通,则该值可行,最后求出最短路即可。
代码
#include<bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1010;
struct edge {
int v,h,w;
};
int C,R;
vector<edge> g[maxn];
int dis[maxn];
bool vis[maxn];
void spfa(int s, int limit) {
for (int i = 1; i <= C; i++) {
dis[i] = INF;
vis[i] = false;
}
dis[s] = 0;
vis[s] = true;
queue<int> q;
q.push(s);
while (!q.empty()) {
int u = q.front();
q.pop();
vis[u] = false;
for (auto e : g[u]) {
if (e.h < limit) continue;
int v = e.v;
if (dis[v] > dis[u] + e.w) {
dis[v] = dis[u] + e.w;
if (!vis[v]) {
vis[v] = true;
q.push(v);
}
}
}
}
}
int main() {
int u,v,h,w;
int s,t,limit;
int count = 0;
while(cin>>C>>R&&C!=0&&R!=0){
for(int i=1;i<=C;i++){
g[i].clear();
}
for(int i=1;i<=R;i++){
cin>>u>>v>>h>>w;
if (h == -1){
h=INF;
}
g[u].push_back({v, h, w});
g[v].push_back({u, h, w});
}
cin>>s>>t>>limit;
int l=0,r=limit,ans=INF,max_h=-1;
while(l<=r){
int mid=(l+r)/2;
spfa(s,mid);
if(dis[t]!=INF){
l=mid+1;
ans=dis[t];
max_h=mid;
}else{
r=mid-1;
}
}
if(count){
cout<<'\n';
}
cout<<"Case "<<++count<<":\n";
if(ans!=INF){
cout<<"maximum height = "<<max_h<<'\n';
cout<<"length of shortest route = "<<ans<<'\n';
} else {
cout<<"cannot reach destination"<<'\n';
}
}
return 0;
}