hdu-3790 dijstra-最短路径-距离+花费


最短路径问题

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


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
 

Source

//dijstra算法:单源最短路径问题-起始点到其他点的最短路径,用一个dist数组保存起始点到其他点的最短路径
//利用贪心思想,每次找到离起始点最近的点,然后更新dist数组 ,重复这个过程 

 
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<stack>
#include<vector>
#include<algorithm>
#define inf 0x7fffffff 


using namespace std;


struct Node{
	int d;//距离 
	int p;//花费 
}map[1005][1005];


int n,m,vis[1005];
int d,p,from,to,s,t,dist[1005],cost[1005];


void init()
{
	for(int i = 1; i <= n; i++)
	{
		for(int j = 1; j <= n; j++)
		{
			map[i][j].d = (i==j?0:inf);//注意初始化 
		}		
	}			
	memset(vis,0,sizeof(vis));//标记 
}


void input()
{
	for(int i = 0; i < m; i++)
	{
		scanf("%d%d%d%d",&from,&to,&d,&p);
		if(d < map[from][to].d)//重边问题 
		{
			map[from][to].d = map[to][from].d = d;//无向图 
			map[from][to].p = map[to][from].p = p;
		}
		else if(d == map[from][to].d)//路径长度相同时,取最小花费 
		{
			map[from][to].p = map[to][from].p = min(map[from][to].p,p);
		}
	}
	scanf("%d%d",&s,&t); 
	//初始化cost和dist数组 
	for(int i = 1; i <= n; i++)
	{
		dist[i] = map[s][i].d;
		cost[i] = map[s][i].p;
	}
}


void dijstra(int s)
{
	vis[s] = 1;
	for(int i = 0; i < n; i++)
	{
		int min = inf,u;
		for(int j = 1; j <= n; j++)//找到更新之后离起始点最近的顶点u 
		{
			if(!vis[j] && dist[j] < min)
			{
				min = dist[j];
				u = j;
			}
		}
		vis[u] = 1;
		for(int k = 1; k <= n; k++)//在顶点u可达的顶点v中,若起始点到顶点u的距离+顶点u到顶点v距离 >= 起始点到顶点v的距离,则更新这些定点到起始点的距离或花费 
		{
			if(!vis[k] && map[u][k].d != inf)//第二个判定条件是为了防止溢出
			{
				if(map[u][k].d+dist[u] < dist[k])//更新距离的同时一定要更新花费,以距离为主 
				{
					dist[k] = map[u][k].d+dist[u];
					cost[k] = map[u][k].p+cost[u];
								else if(map[u][k].d+dist[u] == dist[k])//当距离相等时,取最小花费 
				{
					if(map[u][k].p+cost[u] < cost[k])
						cost[k] = map[u][k].p+cost[u];
				}
			}
		}
	}
}


int main()
{
	
	while(scanf("%d%d",&n,&m) && n != 0 || m != 0)
	{
		init();
		input();
		dijstra(s);
		cout<<dist[t]<<" "<<cost[t]<<endl;
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/cutedumpling/article/details/79631654