hdu3790 最短路径问题 (Dijkstra & SPFA)

#include <stdio.h>
#define INF 0x7fffffff
#define MAX 1002

struct node
{
	int len,val;
}map[MAX][MAX];

int dist[MAX],visited[MAX],cost[MAX];

void Dijkstra(int s,int t,int n)
{
	int i,j,min,u;
	for (i=1;i<=n;i++)
	{
		dist[i]=map[s][i].len;
		cost[i]=map[s][i].val;
		visited[i]=0;
	}
	visited[s]=1;
	dist[s]=0;
	cost[s]=0;
	for (i=1;i<n;i++)
	{
		min=INF;
		u=i;
		for(j=1;j<=n;j++)
			if (!visited[j]&&dist[j]<min)
			{
				min=dist[j];
				u=j;
			}
		visited[u]=1;
		for(j=1;j<=n;j++)
		{
			if (!visited[j]&&map[u][j].len<INF)
			{
				if(dist[j]>(map[u][j].len+dist[u]))
				{
					dist[j]=map[u][j].len+dist[u];
					cost[j]=map[u][j].val+cost[u];
				}
				else if(dist[j]==(map[u][j].len+dist[u]))
				{
					if(cost[j]>(map[u][j].val+cost[u]))
						cost[j]=map[u][j].val+cost[u];
				}
			}//if
		}//for
	}//for
	printf("%d %d\n",dist[t],cost[t]);
}

int main()
{
	int n,m,i,j,d,p,s,t;
	while(scanf("%d %d",&n,&m)&&n)
	{
		for (i=1;i<=n;i++)
		{
			for(j=1;j<=n;j++)
			{
				map[i][j].len=INF;
				map[i][j].val=INF;
			}
		}
		while(m--)
		{
			scanf("%d %d %d %d",&i,&j,&d,&p);
			if(map[i][j].len>d)
			{
				map[i][j].len=map[j][i].len=d;
			    map[i][j].val=map[j][i].val=p;
			}
			else if(map[i][j].len==d)
				if(map[i][j].val>p)
					map[i][j].val=map[j][i].val=p;
		}
		scanf("%d %d",&s,&t);
		Dijkstra(s,t,n);
	}
	return 0;
}
 
 
 
 
 
 
 
 
 
 
 
 
#include <iostream>
#include <queue>
#include <cstdio>
#define INF 99999999
#define MAX 1002
using namespace std;

struct node 
{
	int len,val;
}map[MAX][MAX];
queue<int> q;
int dist[MAX],visited[MAX],cost[MAX]; 

void init(int n)
{
	int i,j;
	for (i=1;i<=n;i++)
	{
		dist[i]=INF;
		cost[i]=INF;
		visited[i]=0;
		for(j=1;j<=n;j++)
		{
			map[i][j].len=INF;
			map[i][j].val=INF;
		}
	}
}

void SPFA(int s,int t,int n)
{
	int i,j;
	while(!q.empty())
		q.pop();
	dist[s]=0;
	cost[s]=0;
	q.push(s);
	visited[s]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for (i=1;i<=n;i++)
		{
			if((dist[u]+map[u][i].len)<dist[i])
			{
				dist[i]=dist[u]+map[u][i].len;
				cost[i]=cost[u]+map[u][i].val;
				if(!visited[i])
				{
					q.push(i);
					visited[i]=1;
				}
			}
			else if((dist[u]+map[u][i].len)==dist[i])
			{
				if(cost[i]>(map[u][i].val+cost[u]))
					cost[i]=map[u][i].val+cost[u];
			}//else
		}//for
		visited[u]=0;
	}
	printf("%d %d\n",dist[t],cost[t]);
}

int main()
{
	int n,m,i,j,d,p,s,t;
	while(scanf("%d %d",&n,&m)&&n)
	{
		init(n);//初始化
		while(m--)
		{
			scanf("%d %d %d %d",&i,&j,&d,&p);
			if(map[i][j].len>d)
			{
				map[i][j].len=map[j][i].len=d;
				map[i][j].val=map[j][i].val=p;
			}
			else if(map[i][j].len==d)
				if(map[i][j].val>p)
					map[i][j].val=map[j][i].val=p;
		}
		scanf("%d %d",&s,&t);
		SPFA(s,t,n);
	}
	return 0;
}






   

你可能感兴趣的:(hdu3790 最短路径问题 (Dijkstra & SPFA))