Yibentong Part Three Data Structure Chapter Four Graph Theory Algorithm Section Two Shortest Path Algorithm 1377: Optimal Travel (travel)

1377: The best ride (travel)

Time limit: 1000 ms Memory limit: 65536 KB
Number of submissions: 2368 Number of passes: 406
[Title description]
H City is a tourist attraction, and thousands of people come to visit each year. For the convenience of tourists, bus companies have set up bus stops and opened some one-way bus lines in various tourist attractions, hotels, restaurants and other places. Each one-way bus line departs from a certain bus stop, passes through several bus stops in turn, and finally reaches the final bus stop.

A traveler recently traveled to City H. He wants to go to S Park, but if there is no bus from his hotel to S Park directly, he may have to take a certain bus for a few stops before going down and changing. Another bus on the same platform, so after changing several times, arrive at S Park.

Now use integers 1, 2, ... N to number all the bus stops in City H. It is agreed that the bus stop number of the hotel where the passenger is located is 1, and the bus stop number of S Park is N.

Write a program to help this passenger find an optimal ride plan, so that he has the least number of changes during the journey from the hotel to S Park.

[Input]
There are two numbers M and N in the first line (1≤M≤100 1<N≤500), indicating that M one-way bus lines have been opened, and there are a total of N stations. From the second row to the Mth row, the information of the 1st to the Mth bus route is given in sequence. The i+1th line gives the information of the i-th bus line, from left to right, all the station numbers on the line are given in order of operation, separated by a space between two adjacent station numbers.

【Output】
Only one line. If you can't get to S Park from the hotel by bus, output "N0", otherwise output the minimum number of changes found by your program. If the number of changes is 0, you can arrive without changing the train.

[Input sample]
3 7
6 7
4 7 3 6
2 1 3 5
[Output sample]
2

#include<bits/stdc++.h>
int g[1001][1001];//fllyd算法
int d[10001];
int n,m,ax,s;
using namespace std;
int main()
{
    
    
	memset(g,10000,sizeof(g));
	cin>>m>>n;
	for(int i=0;i<=m;i++)
	{
    
    
		string str;
		getline(cin,str);
		stringstream input(str);
		int s=0,x;
		while(input>>x)
		{
    
    
			s++;
			d[s]=x;
		}
		for(int j=1;j<s;j++)
			for(int k=j+1;k<=s;k++)
				g[d[j]][d[k]]=1;
	}
	for(int k=1;k<=n;k++)
		for(int i=1;i<=n;i++)
			for(int j=1;j<=n;j++)
				g[i][j]=min(g[i][j],g[i][k]+g[k][j]);
	if(g[1][n]>=10000)
		cout<<"NO";
	else
		cout<<g[1][n]-1;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_44043668/article/details/86072091