【bfs】极其简单的最短路问题

D e s c r i p t i o n Description Description

小C终于被小X感动了,于是决定与他看电影,然而小X距离电影院非常远,现在假设每条道路需要花费小X的时间为1,由于有数以万计的好朋友沿路祝贺,导致小X在通过某些路不得不耗费1的时间来和他们聊天,尽管他希望尽早见到小C,所以他希望找到一条最快时间到达电影院的路。
一开始小X在1号点,共有N个点,M条路,电影院为T号点。

I n p u t Input Input

第一行2个正整数,分别为n,m,t
以下m行,每行3个数,表示连接的编号以及权值
(注意,可能会有重边)

O u t p u t Output Output

一行一个数,表示1到t的最短路

S a m p l e Sample Sample I n p u t Input Input

10 12 6
3 9 2
6 9 2
6 2 1
3 1 1
1 9 2
2 8 2
7 10 1
7 2 1
10 0 1
8 1 1
1 5 2
3 7 2

S a m p l e Sample Sample O u t p u t Output Output

4

E x p l a i n Explain Explain

30%:n<=10 m<=20 
60%: n<=1000 m<=20000 
100%: n<=5000000 m<=10000000

T r a i n Train Train o f of of T h o u g h t Thought Thought

原本想用spfa,结果快读+快输=80分。。。(某高一大佬说要什么蛇皮 (我忘了) 优化 ??)
最后,什么才能担当这spfa都无法驾驭的题目呢?正解——bfs!(神tm我觉得我像个zz)
因为题目说了,边权不是1就是2,当对于边权为2时,我们可以创造一个点,将边权为2的边分解成两条边权为1的边,这样bfs就可以了
什么时候目标点的值改变,就输出,因为bfs中最先到达的点就是最优的
不过
AC还是要靠快读大爷

C o d e Code Code

#include<queue>
#include<cstdio>
#include<iostream>
using namespace std;
int h[5000005],n,m,t,tt,ans[5000005];
int x,y,z;
bool b[5000005];
int read() 
{
	int x=0,flag=1;char ch=getchar();
	while(ch<'0'||ch>'9'){if(ch=='-')flag=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
	return x*flag;
}//快读
struct node
{
	int now,to;
}w[10000005];
void link(int x,int y)
{
	w[++t]=(node){y,h[x]}; h[x]=t;
	w[++t]=(node){x,h[y]}; h[y]=t;
}//连接(无向)
void bfs()
{
	b[1]=true;
	queue<int>Q;
	Q.push(1);
	while (Q.size())
	{
		int tot=Q.front();
		Q.pop();
		for (int i=h[tot]; i; i=w[i].to)
		{
			if (ans[w[i].now]==0)
			 ans[w[i].now]=ans[tot]+1;
			if (ans[tt]>0) {
				printf("%d",ans[tt]);
				return ; 
			} //走到目标点了
			if (!b[w[i].now])
			{
				b[w[i].now]=true;
				Q.push(w[i].now);
			}//加入队列了
		}
	}
}
int main()
{
	n=read(); m=read(); tt=read();
	for (int i=1; i<=m; ++i)
	 {
	 	x=read(); y=read(); z=read();
	 	if (z==2) {
	 		link(x,++n);
			link(n,y); 
	 	}
	 	 else link(x,y);
	 }
	bfs();
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值