City Tour+SPOJ+二分+spfa

来源:互联网 发布:mac dmg制作u盘启动 编辑:程序博客网 时间:2024/06/08 07:05

City Tour

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 552  Solved: 126
[Submit][Status][Web Board]

Description

Alice想要从城市A出发到城市B,由于Alice最近比较穷(不像集训队陈兴老师是个rich second),所以只能选择做火车从A到B。不过Alice很讨厌坐火车,火车上人比较多,比较拥挤,所以Alice有很严格的要求:火车的相邻两站间的最大距离尽可能的短,这样Alice就可以在停站的时候下车休息一下。当然Alice希望整个旅途比较短。

Input

有多组测试数据。
每组测试数据的第一行有两个整数N,M,A,B(N<=2000, M<=50000, N >=2, A,B<=N),其中N是城市的个数,M是城市间通火车的个数。
A,B是Alice起始的城市与目的地城市,城市的标号从1开始。
接下来的M行每行三个整数u,v,w表示从u到v和从v到u有一条铁路,距离为w, u,v<=N, w<=10000。

Output

对于每组测试数据输出满足Alice要求的从A到B的最短距离。

Sample Input

3 3 1 21 2 801 3 402 3 503 3 1 21 2 901 3 102 3 204 5 1 41 2 81 4 91 3 102 4 73 4 8

Sample Output

903015
解决方案:此题可用二分+spfa.二分枚举两站之间最短距离,求最短路时忽略掉大于枚举值。
code:
#include<iostream>#include<cstdio>#include<queue>#include<cstring>#define MMAX 2003#define Max 50005using namespace std;int head[MMAX],k,d[MMAX];bool inqueue[MMAX];int N,M,A,B;struct edge{    int from,to,v;    int next;} E[Max*2];void add(int from,int to,int v){    E[k].from=from;    E[k].to=to;    E[k].v=v;    E[k].next=head[from];    head[from]=k++;}bool spfa(int s,int e,int mid){    memset(inqueue,false,sizeof(inqueue));    memset(d,0x3f,sizeof(d));    queue<int>Q;    Q.push(s);    inqueue[s]=true;    d[s]=0;    while(!Q.empty())    {        int temp=Q.front();        Q.pop();        inqueue[temp]=false;        for(int i=head[temp]; i!=-1; i=E[i].next)        {            int v=E[i].to;            if(E[i].v<=mid)            {                if(d[v]>d[temp]+E[i].v)                {                    d[v]=d[temp]+E[i].v;                    if(!inqueue[v])                    {                        inqueue[v]=true;                        Q.push(v);                    }                }            }        }    }    if(d[e]==0x3f3f3f3f)    {        return false;    }    else    {        return true;    }}int main(){    while(~scanf("%d%d%d%d",&N,&M,&A,&B))    {        k=0;        int MAX=0;        memset(head,-1,sizeof(head));        for(int i=0; i<M; i++)        {            int from,to,v;            scanf("%d%d%d",&from,&to,&v);            add(from,to,v);            add(to,from,v);            MAX=max(MAX,v);        }        int low=0,high=MAX,mid;        while(low<high)        {            mid=(low+high)/2;            if(spfa(A,B,mid))            {                high=mid;            }            else            {                low=mid+1;            }        }        spfa(A,B,low);        printf("%d\n",d[B]);    }    return 0;}

0 0