最优乘车
思路:建图,把所有能到达的点的路线建成一张边权为1的图,由于边权都为1所以直接bfs即可求最短路
具体代码如下
#include<iostream>
#include<cstring>
#include<sstream>
#include<queue>
using namespace std;
const int N = 510;
int n, m;
bool g[N][N];
int dis[N];
int stop[N];
void bfs(){
memset(dis, 0x3f, sizeof dis);
dis[1] = 0;
queue<int> q;
q.push(1);
while(q.size()){
int t = q.front();
q.pop();
for(int i=1; i<=n; ++i)
if(g[t][i] && dis[i] > dis[t] + 1){
dis[i] = dis[t] + 1;
q.push(i);
}
}
}
int main(){
cin >> m >> n;
string line;
getline(cin, line); //读取回车
while(m--){
getline(cin, line);
stringstream ss(line);
int cnt = 0, p;
while(ss >> p) stop[cnt++] = p;
for(int i=0; i<cnt; ++i)
for(int j=i+1; j<cnt; ++j)
g[stop[i]][stop[j]] = true;//能通过为true不能则为false
}
bfs();
if(dis[n] == 0x3f3f3f3f) puts("NO");
else cout << max(dis[n] - 1, 0) << endl;
return 0;
}