UVA 558 Wormholes 【SPFA 判负环】

该博客主要介绍了如何解决UVA在线评测系统558题目的 wormholes 问题,该问题涉及图论中的负环判断。通过使用SPFA(Shortest Path Faster Algorithm)算法,当某节点入队次数超过图的节点数n时,可以判定存在负环。
摘要由CSDN通过智能技术生成

题目链接:
https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=499

题意:就是判断图中有无负环
SPFA,某个节点入队次数大于n就是有负环。

代码:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <math.h>
#include <string>
#include <set>
#include <queue>
#include <stack>
#include <vector>
#include <malloc.h>

using namespace std;

const int MAXN = 41000;
const int INF = 0x3f3f3f3f;

struct Edge
{
    int v;
    int cost;
    Edge(int _v = 0, int _cost = 0)
    {
        v = _v;
        cost = _cost;
    }
};
vector<Edge> E[MAXN];

void addedge(int u, int v, int cost)
{
    E[u].push_back(Edge(v, cost));
}

bool vis[MAXN];
int cnt[MAXN];//记录入队列的次数
int dist[MAXN];


bool SPFA(int start, int n)
{
    memset(vis, false, sizeof(vis));
    memset(cnt, 0, sizeof(cnt));
    for (int i = 0; i <= n; i++) dist[i] = INF;
    vis[start] = true;
    dist[start] = 0;
    queue<int> que;
    while (!que.empty()) que.pop();
    que.push(start);
    cnt[start] = 1;

    while (!que.empty())
    {
        int u = que.front(); que.pop();
        vis[u] = false;
        for (int i = 0; i<E[u].size(); i++)
        {
            int v = E[u][i].v;
            if (dist[v]>dist[u] + E[u][i].cost)
            {
                dist[v] = dist[u] + E[u][i].cost;
                if (!vis[v])
                {
                    vis[v] = true;
                    que.push(v);
                    cnt[v]++;
                    if (cnt[v] > n) return false;
                }
            }
        }
    }
    return true;
}

int n, m;
int a, b, c;

int main()
{
    int t;
    scanf("%d",&t);
    while (t--)
    {
        scanf("%d%d",&n,&m);
        for (int i = 0; i <= n; i++) E[i].clear();
        while (m--)
        {
            scanf("%d%d%d", &a, &b, &c);
            addedge(a, b, c);
            //addedge(b, a, c);
        }
        if (!SPFA(0, n)) puts("possible");
        else puts("not possible");
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值