一、题面
例题链接:Acwing 最优乘车
H 城是一个旅游胜地,每年都有成千上万的人前来观光。
为方便游客,巴士公司在各个旅游景点及宾馆,饭店等地都设置了巴士站并开通了一些单程巴士线路。
每条单程巴士线路从某个巴士站出发,依次途经若干个巴士站,最终到达终点巴士站。
一名旅客最近到 H 城旅游,他很想去 S 公园游玩,但如果从他所在的饭店没有一路巴士可以直接到达 S 公园,则他可能要先乘某一路巴士坐几站,再下来换乘同一站台的另一路巴士,这样换乘几次后到达 S 公园。
现在用整数 1,2,…N 给 H 城的所有的巴士站编号,约定这名旅客所在饭店的巴士站编号为 1,S 公园巴士站的编号为 N。
写一个程序,帮助这名旅客寻找一个最优乘车方案,使他在从饭店乘车到 S 公园的过程中换乘的次数最少。
输入格式
第一行有两个数字 M 和 N,表示开通了 M 条单程巴士线路,总共有 N 个车站。
从第二行到第 M+1 行依次给出了第 1 条到第 M 条巴士线路的信息,其中第 i+1 行给出的是第 i 条巴士线路的信息,从左至右按运行顺序依次给出了该线路上的所有站号,相邻两个站号之间用一个空格隔开。
输出格式
共一行,如果无法乘巴士从饭店到达 S 公园,则输出 NO,否则输出最少换乘次数,换乘次数为 0 表示不需换车即可到达。
数据范围
1≤M≤100,
1≤N≤500
输入样例:
3 7
6 7
4 7 3 6
2 1 3 5
输出样例:
2
二、题目分析
这题求的并不是到目的地的距离,而是问你需要换乘的次数,在思路上需要有一个转换。
首先我们假设车的路线为3—>2—>5;那么我们从3是可以坐到2、5。从2可以坐到5。那么我们实际上可以把3到5的距离设置为1,意思是点3可以只要坐一辆车就能到点5。以此建图,然后只要求出最短路就可以了。由于题目数据范围不大,本题解法不唯一。
三、代码分析
在这里写出dijkstra和bfs求法
//#pragma GCC optimize(2)
#include<iostream>
#include<iomanip>
#include<cstdio>
#include<string>
#include<algorithm>
#include<cmath>
#include<queue>
#include<vector>
#include<map>
#include<stack>
#include<set>
#include<bitset>
#include<ctime>
#include<cstring>
#include<list>
#include<sstream>
#define ll long long
#define ull unsigned long long
#define INF 0x3f3f3f3f
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef pair<int, int> PII;
const int N = 510;
int n, m;
int stop[N];
int g[N][N];
int dis[N];
bool chec[N];
void bfs()
{
int ans = -1;
queue<PII> q;
for (int i = 1; i <= n; i++)
{
if (g[1][i] != 0)
{
q.push({ i,0 });
g[1][i] = 0;
}
}
while (q.size())
{
auto te = q.front();
q.pop();
int currentStop = te.first;
int step = te.second;
if (currentStop == n)
{
ans = step;
break;
}
for (int i = 1; i <= n; i++)
{
if (g[currentStop][i] != 0)
{
q.push({ i,step + 1 });
g[currentStop][i] == 0;
}
}
}
if (ans == -1)
cout << "NO" << endl;
else
cout << ans << endl;
}
void dijkstra()
{
mem(dis, 0x3f);
dis[1] = 0;
for (int i = 0; i < n-1; i++)
{
int t = -1;
for (int j = 1; j <= n; j++)
if (!chec[j] && (t == -1 || dis[t] > dis[j]))t = j;
chec[t] = 1;
for (int j = 1; j <= n; j++)
dis[j] = min(dis[j], dis[t] + g[t][j]);
}
if (dis[n] > INF / 2)
cout << "NO" << endl;
else
cout << dis[n]-1 << endl;
}
void solve()
{
cin >> m >> n;
mem(g, 0x3f);
string line;
getline(cin, line);
while (m--)
{
getline(cin, line);
stringstream ssin(line);
int cnt = 0, p;
while (ssin >> p)stop[cnt++] = p;
for (int i = 0; i < cnt; i++)
for (int j = i+1; j < cnt; j++)
g[stop[i]][stop[j]] = 1;
}
//bfs();
dijkstra();
}
int main()
{
//std::ios::sync_with_stdio(false);
//cin.tie(0), cout.tie(0);
solve();
return 0;
}