Skip to content

Instantly share code, notes, and snippets.

@amoshyc
Created August 2, 2015 07:52
Show Gist options
  • Save amoshyc/373d3a145fc08842ba9c to your computer and use it in GitHub Desktop.
Save amoshyc/373d3a145fc08842ba9c to your computer and use it in GitHub Desktop.
Poj 3259: Warmholes

Poj 3259: Warmholes

分析

相當於找負環,因為 FJ 可以 start at some field,所以只要圖中存在負環,答案就是 YES

AC Code

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;

struct Edge {
    int from, to, cost;
};

int V, E;
Edge edges[2500 * 2 + 200];
int d[500];

bool solve() {
    // bellman ford : find negative cycle
    memset(d, 0, sizeof(d)); // FJ can start at any vertex

    d[0] = 0;
    for (int i = 0; i < V; i++) {
        for (int j = 0; j < E; j++) {
            Edge& e = edges[j];
            if (d[e.to] > d[e.from] + e.cost) {
                d[e.to] = d[e.from] + e.cost;

                if (i == V-1)
                    return true;
            }
        }
    }

    return false;
}

int main() {
    int T;
    scanf("%d", &T);

    while (T--) {
        int N, M, W;
        scanf("%d %d %d", &N, &M, &W);
        int idx = 0;
        for (int i = 0; i < M; i++) {
            int a, b, w;
            scanf("%d %d %d", &a, &b, &w);
            a--; b--;
            edges[idx++] = Edge{a, b, w};
            edges[idx++] = Edge{b, a, w};
        }
        for (int i = 0; i < W; i++) {
            int a, b, w;
            scanf("%d %d %d", &a, &b, &w);
            a--; b--;
            edges[idx++] = Edge{a, b, -w};
        }

        V = N;
        E = idx;

        if (solve())
            puts("YES");
        else
            puts("NO");
    }

    return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment