Unblocked Works Continued HDU-1874 (Dijkstra)

A province has finally built a lot of roads after implementing a smooth flow project plan for many years. However, it is not good to have more roads. Every time you want to travel from one town to another, there are many road plans to choose from, and some plans have a much shorter distance than others. This bothers pedestrians.

Now that the starting point and the end point are known, please calculate the shortest distance you need to travel from the starting point to the end point.
Input
This question contains multiple sets of data, please process to the end of the file.
The first row of each group of data contains two positive integers N and M (0<N<200, 0<M<1000), which represent the number of existing towns and the number of roads built. The towns are numbered from 0 to N-1.
Next is the M-line road information. Each line has three integers A, B, X (0<=A,B<N,A!=B,0<X<10000), indicating that there is a two-way road of length X between town A and town B.
On the next line, there are two integers S, T (0<=S, T<N), which represent the start and end points respectively.
Output
For each group of data, please output the shortest distance you need to travel in one row. If there is no route from S to T, output -1.
Sample Input

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

Sample Output

2
-1

Title description:

	让你计算从A城镇(起点)到B城镇(终点)的最短距离。

Problem solving ideas:

	最短路算法的模板题。我使用的是Dijkstra算法。

AC code:

#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/109059432