HDU 2962 Trucking

题目大意:给定无向图,每一条路上都有限重,求能到达目的地的最大限重,同时算出其最短路。

题解:由于有限重,所以二分检索,将二分的值代入最短路中,不断保存和更新即可。

#include <cstdio>
#include <cstring> 
#include <utility> 
#include <queue> 
using namespace std;  
const int N=20005;  
const int INF=9999999;  
typedef pair<int,int>seg;  
priority_queue<seg,vector<seg>,greater<seg> >q;     
int l,r,mid,begin,end,d[N],head[N],u[N],v[N],w[N],next[N],le[N],n,m,a,b,c; 
int height,route;
bool vis[N];  
void build(){  
    memset(head,-1,sizeof(head)); 
    for(int e=1;e<=m;e++){  
        scanf("%d%d%d%d",&u[e],&v[e],&le[e],&w[e]); 
        if(le[e]==-1)le[e]=INF; 
        u[e+m]=v[e]; v[e+m]=u[e]; w[e+m]=w[e]; le[e+m]=le[e];  
        next[e]=head[u[e]]; head[u[e]]=e;  
        next[e+m]=head[u[e+m]]; head[u[e+m]]=e+m;  
    }  
}     
void Dijkstra(int src,int limit){  
    memset(vis,0,sizeof(vis));  
    for(int i=0;i<=n;i++) d[i]=INF;  
    d[src]=0;  
    q.push(make_pair(d[src],src));  
    while(!q.empty()){  
        seg now=q.top(); q.pop();  
        int x=now.second;  
        if(vis[x]) continue; vis[x]=true;  
        for(int e=head[x];e!=-1;e=next[e]) 
        if(d[v[e]]>d[x]+w[e]&&le[e]>=limit){  
            d[v[e]]=d[x]+w[e];  
            q.push(make_pair(d[v[e]],v[e]));  
        }   
    }  
}      
int main(){  
    int cnt=1;
    while(~scanf("%d%d",&n,&m)){
        height=route=0;
        if(m==0&&n==0)break; 
        if(cnt!=1) puts("");
        printf("Case %d:
",cnt++);
        build();
        scanf("%d%d%d",&begin,&end,&r);
        l=1;
        while(l<=r){
            mid=(l+r)>>1;
            Dijkstra(begin,mid);
            if(d[end]!=INF){height=mid;route=d[end];l=mid+1;}
            else r=mid-1; 
        }
        if(height==0)puts("cannot reach destination");
        else{
            printf("maximum height = %d
",height);
            printf("length of shortest route = %d
",route);
        }
    }  
    return 0;  
}
原文地址:https://www.cnblogs.com/forever97/p/3619187.html