思路
最短路模板题,我们把第一个到达的点的边权设置成 (0) ,其他为 (1) 即可,跑一边最短路即可。
代码
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <utility>
using namespace std;
const int MAXN = 101;
struct node {
int next ,to ,val;
}edge[MAXN * MAXN];
int head[MAXN] ,cnt = 0;
void add (int from ,int to ,int val) {
edge[++ cnt].next = head[from];
head[from] = cnt;
edge[cnt].to = to;
edge[cnt].val = val;
}
int n ,a ,b;
int dis[MAXN] ,vis[MAXN];
int dijkstra (int st ,int en) {
memset (dis ,0x3f ,sizeof (dis));
memset (vis ,0 ,sizeof (vis));
priority_queue <pair <int ,int > ,vector <pair <int ,int > > ,greater <pair <int ,int > > > s;
dis[st] = 0;
s.push(make_pair (dis[st] ,st));
while (! s.empty()) {
int u = s.top().second;
s.pop();
if (vis[u]) continue ;
vis[u] = 1;
for (int q = head[u];~ q;q = edge[q].next) {
int v = edge[q].to;
if (dis[v] > dis[u] + edge[q].val) {
dis[v] = dis[u] + edge[q].val;
s.push(make_pair (dis[v] ,v));
}
}
}
if (dis[en] >= 0x3f3f3f3f) return -1;
return dis[en];
}
int main () {
memset (head ,-1 ,sizeof (head));
scanf ("%d%d%d",&n ,&a ,&b);
int k ,x;
for (int q = 1;q <= n;++ q) {
scanf ("%d",&k);
for (int w = 1;w <= k;++ w) {
scanf ("%d",&x);
if (w == 1) {
add (q ,x ,0);
}
else add (q ,x ,1);
}
}
printf ("%d
",dijkstra (a ,b));
return 0;
}