luogu P1346 电车 【SPFA】

题目链接传送门

有点懒,以后不附上题目了(逃)


整体代码难度:★★
SPFA思考难度:★☆
储存方式思考难度:★★★

读题差点没读懂

第一行有3个整数2<=N<=100,1<=A,B<=N,分别表示路口的数量,和电车的起点,终点。

可以用 F l o y d Floyd ,但我还是想练一练 S P F A SPFA

当然我还是没有用 S T L STL


让我们步入正题:

这道题其实就是把
有默认开关的值放0
无默认开关的值放1
建出邻接表
最后跑一边 S P F A SPFA

在这里插入图片描述
但是
我们仍需注意
无法从起点前往终点,要输出 1 -1
这样解决就好啦!

	memset(dis,100,sizeof(dis));
	if(dis[zd]==1684300900)
	  cout<<-1;
	else
	  cout<<dis[zd];

全部代码:

#include<iostream>
#include<cstring>
using namespace std;
int n,qd,zd,m,b,dl[1111000];
int dis[11110],v[11110];
int hd[11110],tot;
struct node
{
	int x,to,w,next;
}e[11110];
void ljb(int x,int y,int z)                         //建立邻接表
{
	e[++tot].x=x;
	e[tot].to=y;
	e[tot].w=z;
	e[tot].next=hd[x];
	hd[x]=tot;
}
int spfa(int x)                                //跑SPFA
{
	int head=0,tail=1;
	dis[x]=0,dl[1]=x,v[x]=1;
	while(head<=tail)
	{
		head++;
		int x1=dl[head];
		for(int i=hd[x1];i;i=e[i].next)
		 if(dis[x1]+e[i].w<dis[e[i].to])
		  {
		  	dis[e[i].to]=dis[x1]+e[i].w;
		  	if(!v[e[i].to])
		  	 {
		  	 	tail++;
		  	 	v[e[i].to]=1;
		  	 	dl[tail]=e[i].to;
		  	 }
		  }
		v[x1]=0;
	}
}
int main()
{
	cin>>n>>qd>>zd;
	memset(dis,100,sizeof(dis));
	for(int i=1; i<=n; i++)
	 {
	 	cin>>m;
	 	for(int j=1; j<=m; j++)
	 	 {
	 	 	cin>>b;
	 	 	if(j==1)
	 	 	  ljb(i,b,0);                     //默认开关放0
	 	 	else
	 	 	  ljb(i,b,1);                     //其余放1
	 	 }
	 }
	spfa(qd);
	if(dis[zd]==1684300900)            //注意memset(...100...)我这里输出的是1684300900
	  cout<<-1;
	else
	  cout<<dis[zd];
	return 0;
}
发布了37 篇原创文章 · 获赞 11 · 访问量 1247

猜你喜欢

转载自blog.csdn.net/Jackma_mayichao/article/details/103998689
今日推荐