uva558

Posted 啊嘞

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了uva558相关的知识,希望对你有一定的参考价值。

题目链接请戳 这里

 

解题思路

用bellman-ford算法判断,邻接表实现。

 

代码

#include<iostream>
#include<vector>
using namespace std;

const int N = 1010;
const int INF = 1e9;

struct edge {
    int u, v, time;
    edge(int uu, int vv, int cc):u(uu),v(vv),time(cc) {}
    edge() {}
};

vector<edge> edges;
int dist[N];
int n, m;

bool Bellman(int k)
{
    for (int i = 0; i < n; i++) dist[i] = INF;
    dist[k] = 0;
    //最短路最多n-1条边
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < m; j++) {
            int u = edges[j].u;
            int v = edges[j].v;
            if (dist[v] > dist[u] + edges[j].time)
                dist[v] = dist[u] + edges[j].time;
        }
    }
    //试着松弛,如果可以继续松弛,则有负环
    for (int j = 0; j < m; j++) {
        int u = edges[j].u;
        int v = edges[j].v;
        if (dist[v] > dist[u] + edges[j].time)
            return true;
    }
    return false;
}

int main()
{
    int tests;
    cin >> tests;
    while (tests--) {
        cin >> n >> m;
        edges.clear();
        for (int i = 0; i < m; i++) {
            int u, v, time;
            cin >> u >> v >> time;
            edge temp(u, v, time);
            edges.push_back(temp);
        }
        if (Bellman(0))
            cout << "possible" << endl;
        else
            cout << "not possible" << endl;
    }
    return 0;
}

 

以上是关于uva558的主要内容,如果未能解决你的问题,请参考以下文章

uva 558 tree(不忍吐槽的题目名)——yhx

Codeforces 558(CDE)总结

CF-558E (线段树/分块)

UVa 1442 - Cave

罗技 M558 鼠标维修记录

leetcode558