UVa 10986 Sending email / 优先队列优化dijkstra

dijkstra 求最短路 邻接矩阵存不下 换成链表或者vector 用优先队列优化

另外据说spfa也可以 有空写一下

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

const int MAX = 20010;
struct node
{
	int end;
	int dis;
	bool friend operator < (node a,node b)
	{
		return a.dis > b.dis;
	}
};

vector <node> a[MAX];
int dis[MAX];
bool vis[MAX];
int n,m,s,e;

void dijkstra()
{
	memset(vis,false,sizeof(vis));
	priority_queue <node> q;
	int i,j;
	for(i = 0; i < n; i++)
		dis[i] = 999999999;
	dis[s] = 0;
	node no;
	no.end = s;
	no.dis = 0;
	q.push(no);
	while(!q.empty())
	{
		node u = q.top();
		q.pop();
		int x = u.end;
		if(vis[x])
			continue;
		vis[x] = true;
		int len = a[x].size();
		for(int i = 0; i < len; i++)
		{
			node t = a[x][i];
			if(dis[t.end] > u.dis + t.dis)
			{
				dis[t.end] = u.dis + t.dis;
				t.dis = dis[t.end];
				q.push(t);
			}
		}
	}
}
int main()
{
	int t,i,j;
	int x,y,z;
	int cas = 1;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d %d %d %d",&n,&m,&s,&e);
		for(i = 0; i < n; i++)
			a[i].clear();
		while(m--)
		{
			//node no;
			scanf("%d %d %d",&x,&y,&z);
			//no.end = y;
			//no.dis = z;
			a[x].push_back((node){y,z});
			//no.end = x;
			a[y].push_back((node){x,z});
		}
		dijkstra();
		if(dis[e] != 999999999)
			printf("Case #%d: %d\n",cas++,dis[e]);
		else
			printf("Case #%d: unreachable\n",cas++);
	}
	return 0;
}


 

 

你可能感兴趣的:(UVa 10986 Sending email / 优先队列优化dijkstra)