Shortest path HDU-2544 (Dijkstra)

In the annual school competition, all students who enter the finals will get a very beautiful t-shirt. But every time our staff transported hundreds of clothes from the store back to the stadium, they were very tired! So now they want to find the shortest route from the store to the stadium, can you help them?

Input
includes multiple sets of data. The first row of each group of data is two integers N and M (N<=100, M<=10000). N represents how many intersections on the streets of Chengdu, the intersection marked 1 is the location of the store, and the intersection marked N It is the location of the stadium, M said there are several roads in Chengdu. N=M=0 means the end of input. The next M lines, each line includes 3 integers A, B, C (1<=A, B<=N, 1<=C<=1000), which means that there is a road between intersection A and intersection B. We The staff needs C minutes to walk this way.
Enter to ensure that there is at least one route from the store to the stadium.
Output
For each group of input, output one row, which means the shortest time for the staff to walk from the store to the stadium.
Sample Input

2 1
1 2 3
3 3
1 2 5
2 3 5
3 1 2
0 0

Sample Output

3
2

Title description:
Find the shortest route from the store to the stadium

Problem solving idea:
shortest path algorithm template problem.
AC code:
Dijkstra algorithm

#include<stdio.h>
#include<string.h>
#define INF  99999999
int e[220][220],n,m;
int main()
{
    
    
	while (scanf("%d %d",&n,&m)!=EOF)
	{
    
    
		int i,j,a,b,x,s,t,k;
		for (i=0;i<n;i++)
		{
    
    
			for (j=0;j<n;j++)
			{
    
    
				if (i==j)
				e[i][j]=0;
				else
				e[i][j]=INF;
			}
		}
		for (i=0;i<m;i++)
		{
    
    
			scanf ("%d%d%d",&a,&b,&x);
			if (e[a][b]>x)
			{
    
    
				e[a][b]=e[b][a]=x;
			}
		}
		for (k=0;k<n;k++)
		{
    
    
			for (i=0;i<n;i++)
			{
    
    
				for (j=0;j<n;j++)
				{
    
    
					if (e[i][j]>e[i][k]+e[k][j])
					e[i][j]=e[i][k]+e[k][j];
				}
			}
		}
		scanf("%d%d",&s,&t);
		if (e[s][t]!=INF)
		{
    
    
			printf("%d\n",e[s][t]);
		}
		else
		printf ("-1\n");
	}
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_46703995/article/details/109059483