[Acwing] 847. 图中点的层次 bfs || spfa

前言

传送 :

bfs方法待补

前言

无非就是算一遍 从1开始的最短路

CODE

 // Problem: 图中点的层次
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/849/
// Memory Limit: 64 MB
// Time Limit: 1000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define endl '\n'
#define px first
#define py second

typedef pair<int,int> pii;
int dxy[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
const int N  = 1e5+10;

int dist[N];
int n,m,t;
vector<int> g[N];
int st[N];
typedef pair<int,int> pii;
map<pii,int> mp;


void spfa()
{
	queue<int> q;
	memset(dist,0x3f,sizeof dist);
	
	dist[1] = 0;
	st[1] =1;
	q.push(1);
	
	while(!q.empty())
	{
		int t = q.front();
		q.pop();
		st[t] =0 ;
		
		for(auto x : g[t])
		{
			if(dist[x] > dist[t] + 1)
			{
				dist[x] = dist[t] +1;
				if(!st[x])
				{
					q.push(x);
					st[x] = 1;
				}
			}
		}
	}
	
	if(dist[n]!=0x3f3f3f3f)
	cout<<dist[n]<<endl;
	else
	cout<<-1<<endl;
}

void solve()
{
	cin>>n>>m;
	while(m -- )
	{
		int a,b;
		cin>>a>>b;
		g[a].push_back(b);
	}
	
	spfa();
	
}

int main()
{
    ios::sync_with_stdio(false);
    solve();
    return 0;
}

疑虑

847. 图的层次

刚刚在这题中 使用了spfa 水过去了

但是才发现 有自环和重边的情况

我没判断都过了

请问 最短路算法中 是否都可以跑 自环和重边

原因是什么

什么时候有需要判断自环和重边呢 ?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值