题目描述:
The country frog lives in has n towns which are conveniently numbered by 1,2,…,n.
Among n(n−1)/2 pairs of towns, m of them are connected by bidirectional highway, which needs a minutes to travel. The other pairs are connected by railway, which needs b minutes to travel.
Find the minimum time to travel from town 1 to town n.
Input
The input consists of multiple tests. For each test:
The first line contains 4 integers n,m,a,b(2≤n≤105,0≤m≤5⋅105,1≤a,b≤1092≤n≤105,0≤m≤5⋅105,1≤a,b≤109). Each of the following m lines contains 2 integers ui,vi, which denotes cities ui and vi are connected by highway. (1≤ui,vi≤n,ui≠vi1≤ui,vi≤n,ui≠vi).
Output
For each test, write 1 integer which denotes the minimum time.
Sample Input
3 2 1 3
1 2
2 3
3 2 2 3
1 2
2 3
Sample Output
2
3
题目分析:
一个完全图,其中有m条边权值为a,其它边权值为b(权值为a的图是一个稀疏图),求1点到n点的最短路。
我们可以把整个图分割成两个子图,边权值为a的图与边权值为b的图,由于是完全图,1到n的距离无非是a图的最短路(若1到n在a图没有相连的边(也就是说1到n点边权为b))与b相比小的;或者是点1到点n在b图的最短路与a相比小的。(另一种情况)
权值为a的图我们可以用dijkstra或者spfa求得,那么权值为b的稠密图(也就是a图的子图)该怎么求最短路呢?
这个就是补图的BFS求法。用set保存未被扩展的点,从1点扩展的时候,将b图没有的边从set中除去,将剩下的点入队,如此往复就能求得b图中的最短路。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <set>
typedef long long LL;
using namespace std;
const int MAXN=5e5+5;
const int INF=0x3f3f3f3f;
int head[MAXN],id;
LL dis[MAXN];
bool vis[MAXN];
int n,m;
LL a,b;
struct Edge
{
int v,next;
LL w;
}G[MAXN<<1];
void init()
{
memset(head,-1,sizeof(head));
id=0;
}
void addedge(int u,int v,LL w)
{
G[id].v=v;
G[id].w=w;
G[id].next=head[u];
head[u]=id++;
}
struct Qnode
{
int v;
LL c;
Qnode(int _v=0,LL _c=0):v(_v),c(_c){}
bool operator<(const Qnode &r) const
{
return c>r.c;
}
};
LL dijkstra(int n)
{
memset(vis,false,sizeof(vis));
for(int i=1; i<=n; i++) dis[i]=INF;
priority_queue<Qnode>que;
while(!que.empty()) que.pop();
dis[1]=0;
que.push(Qnode(1,0));
Qnode tmp;
while(!que.empty())
{
tmp=que.top();
que.pop();
int u=tmp.v;
if (vis[u]) continue;
vis[u]=true;
for(int i=head[u]; i!=-1; i=G[i].next)
{
int v=G[i].v;
LL w=G[i].w;
if (!vis[v] && dis[v]>dis[u]+w)
{
dis[v]=dis[u]+w;
que.push(Qnode(v,dis[v]));
}
}
}
return dis[n];
}
LL BFS(int n,LL b)
{
set<int>ta,tb;//ta集合保存b图中相连的点 tb保存a图中相连的点
queue<int>Q;
Q.push(1);
dis[1]=0;
dis[n]=INF;
for(int i=2; i<=n; i++) ta.insert(i);
while(!Q.empty())
{
int u=Q.front();
Q.pop();
for(int i=head[u]; i!=-1; i=G[i].next)
{
int v=G[i].v;
if(!ta.count(v)) continue;
ta.erase(v);
tb.insert(v);
}
for(set<int>::iterator it=ta.begin(); it!=ta.end(); it++)
{
Q.push(*it);
dis[*it]=dis[u]+b;
}
ta.swap(tb);
tb.clear();
}
return dis[n];
}
int main()
{
LL ans;
while(scanf("%d%d%lld%lld",&n,&m,&a,&b)!=-1)
{
init();
bool f=false;
for(int i=0; i<m; i++)
{
int u,v;
scanf("%d%d",&u,&v);
if (u>v) swap(u,v);
addedge(u,v,a);
addedge(v,u,a);
if (u==1 && v==n) f=true;
}
if (!f)
{
ans=min(dijkstra(n),b);
}
else
{
ans=min(BFS(n,b),a);
}
printf("%lld\n",ans);
}
return 0;
}