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
2≤N≤500
输入样例:
3 7
6 7
4 7 3 6
2 1 3 5
输出样例:
2
_____________________________________________________________________________
写作不易,点个赞呗!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
_____________________________________________________________________________
#include<bits/stdc++.h>
#define PII pair<int,int>
using namespace std;
const int N=1e5+5,inf=0x3f3f3f3f;
int n,m;
string s;
vector<pair<int,int> >a[N];
int dist[N];
priority_queue<PII,vector<PII>,greater<PII> >Q;
int x[N];
bool dis[N];
void f(int q){
memset(dist,inf,sizeof(dist));
memset(dis,0,sizeof(dis));
dist[q]=0;
Q.push({0,q});
while(!Q.empty()){
auto t=Q.top();
Q.pop();
int vi=t.second;
if(dis[vi])continue;
dis[vi]=true;
for(auto i:a[vi]){
int v=i.second,w=i.first;
if(dist[v]>dist[vi]+w){
dist[v]=dist[vi]+w;
Q.push({dist[v],v});
}
}
}
}
int main(){
cin>>m>>n;
getline(cin,s);
while(m--){
getline(cin,s);
stringstream ssin(s);
int cnt=0,p;
while(ssin>>p)x[cnt++]=p;
for(int i=0;i<cnt;i++){
for(int j=i+1;j<cnt;j++){
a[x[i]].push_back({1,x[j]});
}
}
}
f(1);
if(dist[n]==inf)cout<<"NO";
else cout<<dist[n]-1;
}