您的位置:首页 > 其它

SCU 4444: Travel(最短路)

2017-08-22 10:41 465 查看

Travel

Thecountryfroglivesinhasn

townswhichareconvenientlynumberedby1,2,…,n

.

Amongn(n−1)2

pairsoftowns,mofthemareconnectedbybidirectionalhighway,whichneedsaminutestotravel.Theotherpairsareconnectedbyrailway,whichneedsb

minutestotravel.

Findtheminimumtimetotravelfromtown1

totownn

.

Input

Theinputconsistsofmultipletests.Foreachtest:

Thefirstlinecontains4

integersn,m,a,b(2≤n≤105,0≤m≤5⋅105,1≤a,b≤109).Eachofthefollowingmlinescontains2integersui,vi,whichdenotescitiesuiandviareconnectedbyhighway.(1≤ui,vi≤n,ui≠vi

).

Output

Foreachtest,write1

integerwhichdenotestheminimumtime.

SampleInput

3213
12
23
3223
12
23

SampleOutput

2
3


分两种情况:
1.1到n铁路可以直连跑一次最短路取Min(b,dist
)
2.1到n高速公路连通那么我们BFS跑最短路,每次构一次新图,每个点入队一次.因为是完全图所以每次可以入队的点都非常多.所以可以暴力.

[/code]

#include<iostream>
#include<cstdio>
#include<string.h>
#include<queue>
#include<algorithm>
#include<math.h>
usingnamespacestd;
typedeflonglongLL;
constLLINF=1e16;
constLLN=100005;
structEdge{
LLv,next;
LLw;
}edge[10*N];
LLhead
;
LLtot,n,m,a,b;
boolvis
;
LLlow
;
LLMIN;
voidaddEdge(LLu,LLv,LLw,LL&k){
edge[k].v=v,edge[k].w=w,edge[k].next=head[u],head[u]=k++;
}
structNode{
intu;
intstep;
};
voidinit(){
memset(head,-1,sizeof(head));
tot=0;
}
voidspfa(LLpos){
for(LLi=1;i<=n;i++){
low[i]=INF;
vis[i]=false;
}
low[pos]=0;
queue<LL>q;
while(!q.empty())q.pop();
q.push(pos);
while(!q.empty()){
LLu=q.front();
q.pop();
vis[u]=false;
for(LLk=head[u];k!=-1;k=edge[k].next){
LLw=edge[k].w,v=edge[k].v;
if(low[v]>low[u]+w){
low[v]=low[u]+w;
if(!vis[v]){
vis[v]=true;
q.push(v);
}
}
}
}
}
boolvis1
;
intbfs(intpos){
memset(vis,0,sizeof(vis));
queue<Node>q;
Nodenode;
vis[pos]=1;
node.u=pos;
node.step=0;
q.push(node);
while(!q.empty()){
memset(vis1,false,sizeof(vis1));
node=q.front();
intu=node.u;
intstep=node.step;
///if((step+1)*b>a)return-1;TLE
q.pop();
vis1[u]=1;
for(intk=head[u];k!=-1;k=edge[k].next){
intv=edge[k].v;
vis1[v]=true;
}
Nodenext;
if(!vis1
)returnstep+1;
for(inti=n;i>=1;i--){
if(!vis1[i]&&!vis[i]){
if((step+1)*b>a)return-1;
next.u=i;
next.step=step+1;
q.push(next);
vis[i]=true;
}
}
}
return-1;
}
intmain(){
while(scanf("%lld%lld%lld%lld",&n,&m,&a,&b)!=EOF){
init();
boolflag=false;
for(inti=0;i<m;i++){
LLu,v;
scanf("%lld%lld",&u,&v);
addEdge(u,v,a,tot);
addEdge(v,u,a,tot);
if(u==1&&v==n||u==n&&v==1)flag=1;
}
LLans=0;
if(!flag){
spfa(1);
ans=min(low
,b);
}else{
intstep=bfs(1);
if(step==-1)ans=a;
elseans=min(a,step*b);
}
printf("%lld\n",ans);
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: