熟悉下最短路问题,用dijkstra a了,不过一定一定要注意审题
#include <iostream>
#include <algorithm>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <stack>
#include <map>
#include <set>
#include <deque>
using namespace std;
const int maxn= 105;
const int INF= 0x3f3f3f3f;
struct Edge
{
int v, c;
Edge(int _v= 0, int _c= 0) : v(_v), c(_c) {}
};
struct HeapNode
{
int u, c;
HeapNode(int _u= 0, int _c= 0) : u(_u), c(_c) {}
bool operator < (const HeapNode &rhs) const
{
return c> rhs.c;
}
};
vector<Edge> G[maxn];
bool vis[maxn];
int dis[maxn];
void Dijkstra(int n, int s)
{
priority_queue<HeapNode> Q;
HeapNode cur;
for (int i= 1; i<= n; ++i){
dis[i]= INF;
}
memset(vis, 0, sizeof(vis));
dis[s]= 0;
Q.push(HeapNode(s, 0));
int u, v;
while (!Q.empty()){
cur= Q.top();
Q.pop();
if (vis[cur.u]){
continue;
}
u= cur.u;
vis[u]= 1;
int sz= G[u].size();
for (int i= 0; i< sz; ++i){
v= G[u][i].v;
if (!vis[v] && dis[v]> dis[u]+G[u][i].c){
dis[v]= dis[u]+G[u][i].c;
Q.push(HeapNode(v, dis[v]));
}
}
}
}
int main(int argc, char const *argv[])
{
int n, a, b;
scanf("%d %d %d", &n, &a, &b);
for (int i= 1; i<= n; ++i){
int k, v;
scanf("%d", &k);
for (int j= 0; j< k; ++j){
scanf("%d", &v);
G[i].push_back(Edge(v, 0== j ? 0 : 1));
}
}
Dijkstra(n, a);
printf("%d
", dis[b]< INF ? dis[b] : -1);
return 0;
}