微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

inf=INT_MAX

如何解决inf=INT_MAX

下面的代码是针对 Bellman Ford 算法的,当我使用 const int INF=INT_MAX 时它给出了错误输出,但是当我在第 3 行中使用 const int INF=1e9 时它给出了正确的输出。 知道为什么吗?

代码

#include"bits/stdc++.h"
using namespace std;
const int INF=1e9;
int main()
{
    int n,m;
    cin>>n>>m;
    vector<vector<int>> edges;

    for(int i=0;i<m;i++)
    {
        int u,v,w;
        cin>>u>>v>>w;
        edges.push_back({u,w});

    }
    int src;
    cin>>src;
    vector<int> dist(n,INF);
    dist[src]=0;
    for(int iter=0;iter<n-1;iter++)
    {
        for(auto e:edges)
        {
            int u=e[0];
            int v=e[1];
            int w=e[2];
            dist[v]=min(dist[v],w+dist[u]);

        }
    }
    for(auto i:dist)
    {
        cout<<i<<" ";
    }

}

样本输入:

5 8

1 2 3

3 2 5

1 3 2

3 1 1

1 4 2

0 2 4

4 3 -3

0 1 -1

0

预期输出 0 -1 2 -2 1

解决方法

此处有符号整数溢出 w+dist[u]。简单的修复:

dist[v] = static_cast<int>(min(static_cast<long long>(dist[v]),static_cast<long long>(w) + dist[u]));

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。