有向图,有联系的点之间连边,如果是第一个领接的点,则边的权值为0,后面领接点边的权值为1,建图后做SPFA。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#define oo 0x7f7f7f7f
using namespace std;
const int N = 110;
struct Edge
{
int to,dis;
Edge * next;
};
Edge *adj[N];
Edge edge[N*N];
bool vis[N];
int dis[N];
int cnt;
void addEdge(int u,int v,int w)
{
Edge *ptr = &edge[cnt++];
ptr->to = v;
ptr->dis = w;
ptr->next = adj[u];
adj[u] = ptr;
}
int n,st,ed;
int spfa()
{
queue <int> Q;
memset(vis,false,sizeof(vis));
memset(dis,127,sizeof(dis));
dis[st] = 0;
Q.push(st);
while(!Q.empty())
{
int u = Q.front();Q.pop();
vis[u] = false;
for(Edge*ptr = adj[u];ptr;ptr=ptr->next)
{
int v = ptr->to;
if(dis[v]>dis[u]+ptr->dis)
{
dis[v] = dis[u] + ptr->dis;
if(!vis[v])
{
Q.push(v);
vis[v] = true;
}
}
}
}
if(dis[ed]<oo)
{
return dis[ed];
}
else
{
return -1;
}
}
int main()
{
cnt = 0;
scanf("%d%d%d",&n,&st,&ed);
for(int i=1;i<=n;i++)
{
int ki;
scanf("%d",&ki);
for(int j=1;j<=ki;j++)
{
int v;
scanf("%d",&v);
if(j==1)
{
addEdge(i,v,0);
}
else
{
addEdge(i,v,1);
}
}
}
printf("%d\n",spfa());
return 0;
}
#include <cstdio>
#include <cstring>
#include <queue>
#define oo 0x7f7f7f7f
using namespace std;
const int N = 110;
struct Edge
{
int to,dis;
Edge * next;
};
Edge *adj[N];
Edge edge[N*N];
bool vis[N];
int dis[N];
int cnt;
void addEdge(int u,int v,int w)
{
Edge *ptr = &edge[cnt++];
ptr->to = v;
ptr->dis = w;
ptr->next = adj[u];
adj[u] = ptr;
}
int n,st,ed;
int spfa()
{
queue <int> Q;
memset(vis,false,sizeof(vis));
memset(dis,127,sizeof(dis));
dis[st] = 0;
Q.push(st);
while(!Q.empty())
{
int u = Q.front();Q.pop();
vis[u] = false;
for(Edge*ptr = adj[u];ptr;ptr=ptr->next)
{
int v = ptr->to;
if(dis[v]>dis[u]+ptr->dis)
{
dis[v] = dis[u] + ptr->dis;
if(!vis[v])
{
Q.push(v);
vis[v] = true;
}
}
}
}
if(dis[ed]<oo)
{
return dis[ed];
}
else
{
return -1;
}
}
int main()
{
cnt = 0;
scanf("%d%d%d",&n,&st,&ed);
for(int i=1;i<=n;i++)
{
int ki;
scanf("%d",&ki);
for(int j=1;j<=ki;j++)
{
int v;
scanf("%d",&v);
if(j==1)
{
addEdge(i,v,0);
}
else
{
addEdge(i,v,1);
}
}
}
printf("%d\n",spfa());
return 0;
}