码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 3790-最短路径问题(双权最短路)

时间:2014-08-23 11:22:50      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:des   style   color   java   os   io   strong   for   ar   

最短路径问题

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 13700    Accepted Submission(s): 4201


Problem Description
给你n个点,m条无向边,每条边都有长度d和花费p,给你起点s终点t,要求输出起点到终点的最短距离及其花费,如果最短距离有多条路线,则输出花费最少的。
 

Input
输入n,m,点的编号是1~n,然后是m行,每行4个数 a,b,d,p,表示a和b之间有一条边,且其长度为d,花费为p。最后一行是两个数 s,t;起点s,终点。n和m为0时输入结束。
(1<n<=1000, 0<m<100000, s != t)
 

Output
输出 一行有两个数, 最短距离及其花费。
 

Sample Input
3 2 1 2 5 6 2 3 4 5 1 3 0 0
 

Sample Output
9 11
双权最短路,更新距离的时候,如果距离相等,则判断一下花费需不需要更新,若需要,则更新。用优先队列写的,C++一直tle,换成G++跑了800多MS,sad
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <set>
using namespace std;
const int INF=1<<27;
const int maxn=1100;
int was[maxn],dis[maxn],m,n;
typedef struct node
{
	int p,w,c;
	node (int a,int b,int x){p=a;w=b;c=x;}
	friend bool operator <(node a,node b)
	{
		if(a.w!=b.w) return a.w<b.w;
		return a.c<b.c;
	}
};
vector <node> eg[maxn];
void Dijkstra(int src)
{
	for(int i=1;i<=n;i++) dis[i]=was[i]=INF;
	dis[src]=was[src]=0;
	priority_queue <node> Q;
	Q.push(node(src,dis[src],was[src]));
	while(!Q.empty())
	{
		node v=Q.top();Q.pop();
		for(int i=0;i<eg[v.p].size();i++)
		{
			node t=eg[v.p][i];
			if(dis[t.p]>t.w+v.w)
			{
				dis[t.p]=t.w+v.w;
				was[t.p]=t.c+v.c;
				Q.push(node(t.p,dis[t.p],was[t.p]));
			}
			else if(dis[t.p]==t.w+v.w)
			{
				if(was[t.p]>t.c+v.c)
			   {
				was[t.p]=t.c+v.c;
				Q.push(node(t.p,dis[t.p],was[t.p]));
			   }
			}
		}
	}
}
int main()
{
	//ios::sync_with_stdio(false);
	int u,v,w,c;
	while(~scanf("%d%d",&n,&m))
	{
		if(!n&&!m) break;
		for(int i=1;i<=n;i++)
			eg[i].clear();
		while(m--)
		{
			scanf("%d%d%d%d",&u,&v,&w,&c);
			eg[u].push_back(node(v,w,c));
			eg[v].push_back(node(u,w,c));
		}
		int src,en;
		scanf("%d%d",&src,&en);
		Dijkstra(src);
		printf("%d %d\n",dis[en],was[en]);
	}
	return 0;
}



HDU 3790-最短路径问题(双权最短路)

标签:des   style   color   java   os   io   strong   for   ar   

原文地址:http://blog.csdn.net/qq_16255321/article/details/38776541

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!