最短路
View Code
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
#define INF 0x3f3f3f3f
#define N 105
int path[N], vis[N];
int cost[N][N];
int lowcost[N];
int n, a, b;
void Dijkstra(int cost[][N], int lowcost[N], int n, int beg)
{
int i, j, min;
memset(vis, 0, sizeof(vis));
vis[beg] = 1;
for (i = 0; i < n; i++)
{
lowcost[i] = cost[beg][i];
path[i] = beg;
}
lowcost[beg] = 0;
path[beg] = -1;
int pre = beg;
for (i = 1; i < n; i++)
{
min = INF;
for (j = 0; j < n; j++)
if (vis[j] == 0 && lowcost[pre] + cost[pre][j] < lowcost[j])
{
lowcost[j] = lowcost[pre] + cost[pre][j];
path[j] = pre;
}
for (j = 0; j < n; j++)
if (vis[j] == 0 && lowcost[j] < min)
{
min = lowcost[j];
pre = j;
}
vis[pre] = 1;
}
}
int main()
{
//freopen("t.txt", "r", stdin);
scanf("%d%d%d", &n, &a, &b);
a--;
b--;
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
if (i != j)
cost[i][j] = INF;
else
cost[i][j] = 0;
for (int i = 0; i < n; i++)
{
int x, a;
scanf("%d", &x);
for (int j = 0; j < x; j++)
{
scanf("%d", &a);
a--;
if (j == 0)
cost[i][a] = 0;
else
cost[i][a] = 1;
}
}
Dijkstra(cost, lowcost, n, a);
if (lowcost[b] < INF)
printf("%d\n", lowcost[b]);
else
printf("-1\n");
return 0;
}