SCU - 4444 Travel(补图最短路)

Travel

The country frog lives in has towns which are conveniently numbered by .

Among pairs of towns, of them are connected by bidirectional highway, which needs minutes to travel. The other pairs are connected by railway, which needs minutes to travel.

Find the minimum time to travel from town to town .

Input

The input consists of multiple tests. For each test:

The first line contains integers (). Each of the following lines contains integers , which denotes cities and are connected by highway. ().

Output

For each test, write 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,问1-n最短路.

思路:如果a小跑个DJ或者bfs暴力就行,如果b小,可能边很多,但是其实相比于给出的边来说,这个图还是一个特别稀疏的图.

用两个队列,一个来跑bfs,另一个存点.先把所有元素压进队列all,s点压进q,每次从q中取一个点now,把与之相连的边做个标记,然后从all里一个一个取点,如果取出来的点未标记,说明补图中now可以到达该点(当然距离肯定也是最短的,因为每条边长度一样嘛),就把该点压入q中,因为给的原图很稀疏,所以这样也跑不了几次.

代码:

#include<bits/stdc++.h>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 1000000007
using namespace std;
typedef long long ll;
const int maxn = 1e6+5;
const double esp = 1e-12;
const int ff = 0x3f3f3f3f;
map<int,int>::iterator it;

struct node
{
	int v;
	int ne;
} edge[maxn];

int n,m,len;
ll dis[maxn],a,b;
int head[maxn];
int vis[maxn];

void add(int u,int v)
{
	edge[len].v = v;
	edge[len].ne = head[u];
	head[u] = len++;
}

ll bfs()
{
	queue<int> q;
	queue<int> all;
	
	if(a< b)
	{
		q.push(1);
		dis[1] = 0;
		while(!q.empty())
		{
			int now = q.front();
			q.pop();
			
			for(int i = head[now];i!= -1;i = edge[i].ne)
			{
				int to = edge[i].v;
				if(vis[to])
					continue;
				dis[to] = dis[now]+1;
				q.push(to);
				vis[to] = 1;
			}
		}
		
		return min(dis[n]*a,b);
	}
	else
	{
		for(int i = 2;i<= n;i++)
			all.push(i);
		int mk = 1;
		q.push(1);	
		dis[1] = 0;
		while(!q.empty())
		{
			int now = q.front();
			q.pop();
			
			int cnt = all.size();
			for(int i = head[now];i!= -1;i = edge[i].ne)
				vis[edge[i].v] = mk;
			
			while(cnt--)
			{
				int id = all.front();
				all.pop();
				
				if(vis[id] == mk)
					all.push(id);
				else
				{
					dis[id] = dis[now]+1;
					q.push(id);
				}
			}
			mk++;
		}
		return min(dis[n]*b,a); 
	}
}

void init()
{
	len = 0;
	mem(dis,ff);
	mem(vis,0);
	mem(head,-1);
}

int main()
{
	while(~scanf("%d %d %lld %lld",&n,&m,&a,&b))
	{
		init();
		for(int i = 1;i<= m;i++)
		{
			int x,y;
			scanf("%d %d",&x,&y);
			add(x,y);
			add(y,x);
		}
		
		ll ans = bfs();
		printf("%lld\n",ans);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/nka_kun/article/details/80195343