最短路N题Tram SPFA
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <queue>
#include <vector>
#define N 1010
#define INF 0x3f3f3f3f
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Max(a, b) ((a) > (b) ? (a) : (b))
using namespace std;
int head[N];
int dis[N];
int n;
bool f[N];
struct node
{
int s, e, w, next;
}ans[N];
void Init()
{
for(int i = 0; i <= n; i++) {
dis[i] = INF;
f[i] = 0;
head[i] = -1;
}
}
void Add(int s, int e, int w, int index)
{
ans[index].s = s;
ans[index].e = e;
ans[index].w = w;
ans[index].next = head[s];
head[s] = index;
}
void Spfa(int a, int b)
{
queue<int>q;
q.push(a);
f[a] = 1;
dis[a] = 0;
while(q.size()) {
int p = q.front(); q.pop();
f[p] = 0;
for(int i = head[p]; i != -1; i = ans[i].next) {
if(dis[p] + ans[i].w < dis[ans[i].e]) {
dis[ans[i].e] = dis[p] + ans[i].w;
if(!f[ans[i].e]) {
f[ans[i].e] = 1;
q.push(ans[i].e);
}
}
}
}
if(dis[b] == INF) printf("-1\n");
else
printf("%d\n", dis[b]);
}
int main()
{
int a, b;
while(~scanf("%d %d %d", &n, &a, &b)) {
int m, g, index = 0;
Init();
for(int i = 1; i <= n; i++) {
scanf("%d %d", &m, &g);
Add(i, g, 0, index++);
for(int j = 1; j < m; j++) {
scanf("%d", &g);
Add(i, g, 1, index++);
}
}
Spfa(a, b);
}
}
#include <queue>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cctype>
#include <cmath>
#include <queue>
#include <vector>
#define N 1010
#define INF 0x3f3f3f3f
#define Min(a, b) ((a) < (b) ? (a) : (b))
#define Max(a, b) ((a) > (b) ? (a) : (b))
using namespace std;
int head[N];
int dis[N];
int n;
bool f[N];
struct node
{
int s, e, w, next;
}ans[N];
void Init()
{
for(int i = 0; i <= n; i++) {
dis[i] = INF;
f[i] = 0;
head[i] = -1;
}
}
void Add(int s, int e, int w, int index)
{
ans[index].s = s;
ans[index].e = e;
ans[index].w = w;
ans[index].next = head[s];
head[s] = index;
}
void Spfa(int a, int b)
{
queue<int>q;
q.push(a);
f[a] = 1;
dis[a] = 0;
while(q.size()) {
int p = q.front(); q.pop();
f[p] = 0;
for(int i = head[p]; i != -1; i = ans[i].next) {
if(dis[p] + ans[i].w < dis[ans[i].e]) {
dis[ans[i].e] = dis[p] + ans[i].w;
if(!f[ans[i].e]) {
f[ans[i].e] = 1;
q.push(ans[i].e);
}
}
}
}
if(dis[b] == INF) printf("-1\n");
else
printf("%d\n", dis[b]);
}
int main()
{
int a, b;
while(~scanf("%d %d %d", &n, &a, &b)) {
int m, g, index = 0;
Init();
for(int i = 1; i <= n; i++) {
scanf("%d %d", &m, &g);
Add(i, g, 0, index++);
for(int j = 1; j < m; j++) {
scanf("%d", &g);
Add(i, g, 1, index++);
}
}
Spfa(a, b);
}
}