有负边的最短路算法(bellman-ford,spfa)

 

 1.bellman-ford算法

#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
const int N = 505, M = 10010;
struct Edge
{
    int from;
    int to;
    int cost;
}edge[M];
int dist[N];
const int INF = 1e9;
int n, m, k;
int backup[N];
int bellman_ford()
{
    for (int i = 0;i < N;i++)
        dist[i] = INF;
    dist[1] = 0;
    for (int i = 0;i < k;i++)
    {//本题不是求最短距离,而是求1号点最多经过k条边到达n号点的最短距离
    //所以需要保证只循环k次,并且每次一个点最多只会多加一条边

        memcpy(backup, dist, sizeof(backup));
        for (int j = 0;j < m;j++)   //循环所有边
        {
            int a = edge[j].from;
            int b = edge[j].to;
            dist[b] = min(dist[b], backup[a] + edge[j].cost);
            //这里加入backup的意义在于防止串联,即一个点在一次循环中被多加了几次边
            //这样子就不符合题意只加入k条边了
        }
    }
    if (dist[n] > INF / 2)  //这里因为有负权边的存在,所以可能最后dist[n]会不为inf,但还是会被更新
                            //还是到不了,可能这么判断也可以在上加入dist[a]==inf,不能更新
        return -INF;            //当到不了时也包含了考虑负权边的作用
        //源于结果可能是-1,所以这里改成了-inf,防止结果出错
    return dist[n];
}
int main()
{

    cin >> n >> m >> k;
    for (int i = 0;i < m;i++)
    {
        int a, b, c;
        cin >> a >> b >> c;
        edge[i] = { a,b,c };
    }
    int ans = bellman_ford();
    if (ans == -INF)
        cout << "impossible";
    else cout << ans;
}

作者:seez
链接:https://www.acwing.com/activity/content/code/content/2131984/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

2.spfa算法

#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N=1E5+6;
int e[2*N],w[2*N],ne[2*N],idx;
int h[N];
int dist[N];
int n,m;
const int INF=0x3f3f3f3f;
void add(int a,int b,int c)
{
    e[idx]=b;
    w[idx]=c;
    ne[idx]=h[a];
    h[a]=idx++;
}
bool st[N];
int spfa()
{
    queue<int> q;
    st[1]=true;
    q.push(1);
    dist[1]=0;
    while(q.size())
    {
        int v=q.front();
        q.pop();
        st[v]=false;
        for(int i=h[v];i!=-1;i=ne[i])
        {
            int j=e[i];
            if(dist[j]>dist[v]+w[i])
            {
                dist[j]=dist[v]+w[i];
                if(!st[j])
                {   st[j]=true;
                    q.push(j);
                }
                
            }
        }
    }
    return dist[n];
}
int main()
{ios::sync_with_stdio(false);
    
    memset(h,-1,sizeof h);
    memset(dist,0x3f,sizeof dist);
    cin>>n>>m;
    for(int i=0;i<m;i++)
    {
        int a,b,c;
        cin>>a>>b>>c;
        add(a,b,c);
    }
    int ans=spfa();
    if(ans==INF) cout<<"impossible";
    else cout<<ans;
}

spfa算法求负环

#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;

int n, m;
const int N = 1E5 + 6;
int e[2 * N], ne[2 * N], h[2 * N], w[2 * N];
int dist[N];
int idx;
bool st[N];
void add(int a, int b, int c)
{
	e[idx] = b;
	w[idx] = c;
	ne[idx] = h[a];
	h[a] = idx++;
}
int cnt[N];
int spfa()
{//spfa求是否有负环,不用设置dist的初值,即使全部是0,他也会更新
//刚开始把所有点都放入队列中,然后不断更新他的邻接点的dist,直到找到负环(!!负环一定有邻接点)
//我们可以知道,一个点如果有负环,最坏条件是在第n个点,从第一个点到第n个点只需要经过n-1条边
//但是当他的cnt[n]>=n,就说明有一个点重复经历了两次,而spfa算法保证除非是负环,不然一个点不会被经历两次
	queue<int> q;
	//**********************************
	//1..把所有点都放入队列中
	for (int i = 1;i <= n;i++)
	{
		st[i] = true;
		q.push(i);
	}

	while (q.size())
	{
		int v = q.front();
		q.pop();
		st[v] = false;
		
		for (int i = h[v];i != -1;i = ne[i])
		{
			int j = e[i];
			if (dist[j] > dist[v] + w[i])
			{//2.一个负环不论初值是多少都可以更新
				
				if (!st[j])
				{
					q.push(j);
					st[j] = true;
				}
				dist[j] = dist[v] + w[i];
				cnt[j] = cnt[v] + 1;	//cnt数组记录从1到这个点有几条边
				//如果cnt>=n,最坏情况下满足条件,一定有负环
				if (cnt[j] >= n) return true;
			}
		}
	}
	return false;
}
int main()
{
	memset(h, -1, sizeof h);
	cin >> n >> m;
	for (int i = 0;i < m;i++)
	{
		int a, b, c;
		cin >> a >> b >> c;
		add(a, b, c);
	}
	if (spfa())  cout << "Yes";
	else cout<<"No";
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值