POJ 3259 Bellman-Ford

//Bellman-Ford的模板题
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
using namespace std;
const int maxv=510;
const int maxe=5210;
const int INF=0x3f3f3f3f;
int cnt,dis[maxv];
struct Edge {
    int from,to,val;
} edge[maxe];
void init() {
    cnt=0;
    memset(dis,INF,sizeof dis);
}
void addedge(int from,int to,int val) {
    edge[cnt].from=from;
    edge[cnt].to=to;
    edge[cnt++].val=val;
}
bool Bellman_Ford(int n,int cnt,Edge edge[],int dist[]) {
    dist[1]=0;
    bool flag;
    for(int i=1; i<=n; i++) { //松弛n次
        flag=false;
        for(int j=0; j<cnt; j++) {
            if(dist[edge[j].to]>dist[edge[j].from]+edge[j].val) {
                dist[edge[j].to]=dist[edge[j].from]+edge[j].val;
                flag=true;
            }
        }
        if(flag==false)
            break;
    }
    return flag;
}
int main(void) {
#ifndef ONLINE_JUDGE
    freopen("E:\\input.txt","r",stdin);
#endif // ONLINE_JUDGE
    ios::sync_with_stdio(false);
    int T,n,m,w;
    cin>>T;
    while(T--) {
        init();
        cin>>n>>m>>w;
        int t1,t2,t3;
        for(int i=0; i<m; i++) {
            cin>>t1>>t2>>t3;
            addedge(t1,t2,t3);
            addedge(t2,t1,t3);
        }
        for(int i=0; i<w; i++) {
            cin>>t1>>t2>>t3;
            addedge(t1,t2,-t3);
        }
        if(Bellman_Ford(n,cnt,edge,dis))
            cout<<"YES"<<endl;
        else
            cout<<"NO"<<endl;
    }
    return 0;
}

 

    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/shadandeajian/article/details/81285858
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞