处理负权边——Bellman_ford与spfa算法

Bellman_ford算法

思路:
Bellman_ford算法遍历图中所有的边以更新各点的距离,对于无负权回路的图,最多经过n-1次(n为边数)遍历,便可找到最短距离。
 

#include <iostream>
#include <cstring>
#include <algorithm>

using namespace std;
const int N = 150010;
int dis[N], backup[N]; // backup为备份数组
int n, m;

struct 
{
    
    
    int a, b, w;  
}edges[N];

bool bellman_ford()
{
    
    
    memset(dis, 0x3f, sizeof(dis));
    dis[1] = 0;
    
    for(int i = 1; i < m; i++)
    {
    
    
        memcpy(backup, dis, sizeof(dis)); 
        for(int j = 1; j <= m; j++)
        {
    
    
            int a = edges[j].a, b = edges[j].b, w = edges[j].w;
            dis[b] = min(dis[b], backup[a] + w); // 保证每一次更新的都在上一次基础上得来
        }
    }
    return dis[n] < 0x3f3f3f3f/2;
}

int main()
{
    
    
    cin >> n >> m;
    
    int x, y, z;
    for(int i = 1; i <= m; i++)
    {
    
    
        cin >> x >> y >> z;
        edges[i] = {
    
    x, y, z};
    }

    if(bellman_ford()) cout << dis[n];
    else cout << "impossible";
    return 0;
}

spfa算法

思路:spfa算法由Bellman_ford算法优化而来,不再遍历每一条边,而是遍历每一个被更新过距离的点的后继点,因为若一个点的距离未被更新,则其后继点的距离也一定不会因为该点而发生改变。为此可用队列存每个被更新距离点的后继节点。
若需判断一个图中是否有负权回路,则可开一个cnt[]数组存取当前各点到起点最短路径的边数。如果cnt中有值大于边数-1,则存在负权回路。
 

#include <iostream>
#include <cstring>
#include <utility>
#include <queue>


using namespace std;
const int N = 150010;


int idx, e[N], ne[N], w[N], h[N], dis[N];
bool in[N];
// int cnt[N];
void add(int a, int b, int c) 
{
    
    
    e[idx] = b, w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx++;
}

bool spfa(int n)
{
    
    
    memset(dis, 0x3f, sizeof(dis));
    
    queue<int> qq;
    qq.push(1);
    dis[1] = 0;
    
    while(qq.size())
    {
    
    
        int t = qq.front();
        qq.pop();
        in[t] = false;
        
        for(int i = h[t]; i != -1; i = ne[i])
            if(dis[e[i]] > dis[t] + w[i])
            {
    
    
                dis[e[i]] = dis[t] + w[i];
                qq.push(e[i]);
                in[e[i]] = true;
                // cnt[e[i]] = cnt[t] + 1;
                // if(cnt[e[i] >= n) => 存在负环
             }
    }
    
    return dis[n] < 0x3f3f3f3f/2;
}

int main()
{
    
    
    memset(h, -1, sizeof(h));
    
    int n, m;
    cin >> n >> m;
    
    int x, y, z;
    while(m--)
    {
    
    
        cin >> x >> y >> z;
        add(x, y, z);
    }

    if(spfa(n)) cout << dis[n];
    else cout << "impossible";
    return 0;
}

猜你喜欢

转载自blog.csdn.net/PBomb/article/details/107721810
今日推荐