Bellman-ford(解决负权边) 带权图的最短路径问题

https://blog.csdn.net/yuewenyao/article/details/81026278

附上一道简单板子题

POJ 3259

因为需要存在一个节点返回自身时路径长度为负数,问题转换为了判断图中是否存在负权环,如果存在则输出YES,否则输出NO

/*
 * @Author: CY__HHH
 * @Date: 2019-10-25 10:05:14
 * @LastEditTime: 2019-10-25 14:21:44
 */
#include<iostream>
#include<cstdio>
#include<vector>
#define inf (0x3f3f3f3f)
using namespace std;
typedef struct{
    int u,v,w;
}edge;
vector<edge> Edge;
int main()
{
    int t,n,m,num,u,v,w;  scanf("%d",&t);
    while(t--)
    {
        Edge.clear();
        scanf("%d%d%d",&n,&m,&num);
        for(int i=1;i<=m;++i)
        {
            scanf("%d%d%d",&u,&v,&w);
            Edge.push_back({u,v,w});
            Edge.push_back({v,u,w});
        }
        for(int i=1;i<=num;++i)
        {
            scanf("%d%d%d",&u,&v,&w);
            Edge.push_back({u,v,-w});
        }
        vector<int> dist(n+1,inf);
        dist[1] = 0;
        for(int i=1;i<=n-1;++i)
        {
            for(int j=0;j!=Edge.size();++j)
            {
                if(dist[Edge[j].v] > dist[Edge[j].u] + Edge[j].w)
                    dist[Edge[j].v] = dist[Edge[j].u] + Edge[j].w;//松弛
            }
        }
        bool flag = false;
        for(int j=0;j!=Edge.size();++j)
        {
            if(dist[Edge[j].v] > dist[Edge[j].u] + Edge[j].w)
            {
                flag = true;
                break;
            }
        }
        if(flag)
            printf("YES\n");
        else
            printf("NO\n");
    }  
}

  

posted on 2019-10-25 14:30  chengyulala  阅读(165)  评论(0编辑  收藏  举报

导航