(CBT) Shortest Path

Shortest Path

description:

The shortest path between two vertices in any seeking FIG.

Input:

       The first line of the input data is a positive integer representing the number of vertices in the graph n (vertex respectively 0,1, ..., n-1 for numbering). n lines after each line containing n integers, the i-th row and j denotes the number of vertex i-1 and a side between vertices 1 j-, with 10,000 to represent infinity between two vertices. 2 after each line number that is a shortest path vertices treated with -1 -1 denotes an input end, -1-1 not solved.

Output:

Each shortest path vertices treat two output data lines: a first output line of shortest path length between the two vertices of the second output line the shortest path, according to the order the output sequence of vertex numbers, separated by a space vertices. When there is no path between two vertices, only the output string "NO" on the line.

 

Example input

7

0 12 10000 10000 10000 10000 10000

12 0 10000 10000 3 10000 10000

10000 10000 0 10000 10000 21 11

10000 10000 10000 0 10000 10000 10000

10000 3 10000 10000 0 10000 8

10000 10000 21 10000 10000 0 10000

10000 10000 11 10000 8 10000 0

0 2

0 3

5 0

2 1

1 5

-1 -1

Sample output

34

0 1 4 6 2

NO

55

5 2 6 4 1 0

22

2 6 4 1

43

1 4 6 2 5

Tip: You can use Floyd algorithm, you can also add a layer of circulating outside the Dijkstra algorithm.

#include<stdio.h>
#include<stdlib.h>
#define INF 100
#define MAXV 100
typedef struct {
	int edges[MAXV][MAXV];
	int n, e;
}MatGraph;
void Floyd(MatGraph* g, int A[][MAXV], int path[MAXV][MAXV])
{
	int i, j, k;
	for (i = 0; i < g->n; i++)
	{
		for (j = 0; j < g->n; j++)
		{
			A[i][j] = g->edges[i][j];
			if ( g->edges[i][j] < INF)
				path[i][j] = j;
			else
				path[i][j] = -1;
		}
	}
	for (k = 0; k < g->n; k++)
	{
		for (i = 0; i < g->n; i++)
		{
			for (j = 0; j < g->n; j++)
			{
				if (A[i][k] + A[k][j] < A[i][j])
				{
					A[i][j] = A[i][k] + A[k][j];
					path[i][j] = path[i][k];
				}
			}
		}
	}
}
int main()
{
	int i, j, k;
	int m, n;
	int A[MAXV][MAXV];
	int path[MAXV][MAXV];
	MatGraph* g = (MatGraph*)malloc(sizeof(MatGraph));
	scanf("%d", &g->n);
	for (i = 0; i < g->n; i++)
	{
		for (j = 0; j < g->n; j++)
			scanf("%d", &g->edges[i][j]);
	}
	Floyd(g, A, path);
	for (;;)
	{
		scanf("%d %d", &m, &n);
		if (m == -1 && n == -1)
			break;
		k = path[m][n];
		if (k < 0)
		{
			printf("NO\n");
			continue;
		}
		printf("%d\n", A[m][n]);
		printf("%d ", m);
		while (k != n)
		{
			printf("%d ", k);
			k = path[k][n];
		}
		printf("%d",n);
		printf("\n");
	}
	return 0;

}

  

Guess you like

Origin www.cnblogs.com/KIROsola/p/11909449.html