Uva 558 - Wormholes//Bellman-Ford

分析:模板题,但是要理解题意。环不和强连通分支差不多吧,我写了一个基于强连通分支的代码,但是WA了。。。。

下面是AC代码:

#include<cstdio>
#include<cstring>
#include<queue>
#include<vector>
using namespace std;
const int INF = 100000000;
const int maxn = 1005;
vector<int> G[maxn];
int weight[maxn][maxn];
queue<int> q;
bool inq[maxn];
int d[maxn];
int count[maxn];
int n,m;
bool Bellman_Ford()
{
    for(int i = 0 ; i < n; i++) d[i] = INF,inq[i] = false,count[i] = 0;
    d[0] = 0;
    count[0] = 1;
    q.push(0); inq[0] = true;
    while(!q.empty())
    {
        int u = q.front(); q.pop();
        inq[u] = false;
        for(int i = 0; i < G[u].size(); i++)
        {
            int v = G[u][i];
            if(d[v] > d[u] + weight[u][v])
            {
                d[v] = d[u] + weight[u][v];
                if(!inq[v])
                {
                    inq[v] = true;
                    count[v]++;
                    if(count[u] >= n) return true;
                    q.push(v);
                }
            }
        }
    }
    return false;
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d%d",&n,&m);
        for(int i = 0; i < n; i++) G[i].clear();
        int u,v,w;
        for(int i = 0 ; i < m; i++)
        {
            scanf("%d%d%d",&u,&v,&w);
            G[u].push_back(v);
            weight[u][v] = w;
        }
        if(Bellman_Ford()) printf("possible\n");
        else printf("not possible\n");
    }
    return 0;
}
    原文作者:Bellman - ford算法
    原文地址: https://blog.csdn.net/mr_zys/article/details/8960657
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞