N - Tram POJ - 1847
题意: 从一个点出发,可以到达若干个点,到第一个点的边权为0,到其他点的边权为1,到不了为 inf ,求从起点到终点的最短路。
#include<iostream>
#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int maxn = 110;
const int inf = 0x3f3f3f3f;
int N, A, B;
int head[maxn], cnt, dis[maxn];
bool vis[maxn];
struct edge{
int to, next, w;
}e[maxn*maxn];
void add(int u, int v, int w) {
e[++cnt].next = head[u];
e[cnt].to = v;
e[cnt].w = w;
head[u] = cnt;
}
typedef struct node{
int len, ver;
} node;
bool operator < (const node &a, const node &b) {
return a.len > b.len;
}
void dijkstra(int s) {
dis[s] = 0;
node ss;
ss.len = 0, ss.ver = s;
priority_queue<node> heap;
heap.push(ss);
while(heap.size()) {
node now = heap.top(); heap.pop();
int u = now.ver, dist = now.len;
if(vis[u]) continue;
vis[u] = 1;
for(int i = head[u]; i; i = e[i].next) {
int to = e[i].to;
if(dis[to] > dist + e[i].w) {
dis[to] = dist + e[i].w;
node tmp; tmp.len = dis[to]; tmp.ver = to;
heap.push(tmp);
}
}
}
}
int main() {
// freopen("test.in", "r", stdin);
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
cin >> N >> A >> B;
int k, v;
memset(dis, inf, sizeof(dis));
for(int i = 1; i <= N; i++) {
cin >> k;
for(int j = 1; j <= k; j++) {
cin >> v;
if(j == 1) add(i, v, 0);
else add(i, v, 1);
}
}
dijkstra(A);
if(dis[B] != inf) cout << dis[B] << endl;
else cout << "-1" << endl;
return 0;
}