Skip to content

Instantly share code, notes, and snippets.

@amoshyc
Last active March 20, 2017 12:19
Show Gist options
  • Save amoshyc/a5a1714a4dfe1c402a78 to your computer and use it in GitHub Desktop.
Save amoshyc/a5a1714a4dfe1c402a78 to your computer and use it in GitHub Desktop.
Poj 3169: Layout

Poj 3169: Layout

分析

這就是所謂的 差分約束系統 啊,第一次寫到…

將多個同型式的不等式轉化成最短路徑問題,原理請參

之後照著做就是了

題外話,想不到 Edge{a, b, w} 這種寫法是 C++11 才有的,不過在 poj 上選 G++ 也可以用, 只是會產生 Warning 而已

AC Code

#include <iostream>
#include <algorithm>
#include <vector>
#include <queue>
#include <functional>
#include <cstdio>
#include <cstdlib>
#include <cstring>

using namespace std;

const int INF = 0x3f3f3f3f;

struct Edge {
    int u, v, cost;
};

Edge edges[10000 * 2 + 1];
int N, ML, MD;
int V, E;

int solve() {
    // bellman ford
    int d[V];
    memset(d, INF, sizeof(d));
    d[1] = 0;

    for (int i = 0; i < V; i++) {
        bool update = false;

        for (int j = 0; j < E; j++) {
            Edge& e = edges[j];
            if (d[e.v] > d[e.u] + e.cost) {
                d[e.v] = d[e.u] + e.cost;
                update = true;

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

        if (!update)
            break;
    }

    if (d[N] == INF)
        return -2;
    return d[N];
}

int main() {
    scanf("%d %d %d", &N, &ML, &MD);

    int idx = 1;
    for (int i = 0; i < ML; i++) {
        int A, B, D;
        scanf("%d %d %d", &A, &B, &D);
        edges[idx++] = Edge{A, B, D};
    }
    for (int i = 0; i < MD; i++) {
        int A, B, D;
        scanf("%d %d %d", &A, &B, &D);
        edges[idx++] = Edge{B, A, -D};
    }
    // d[i+1] >= d[i]
    // d[i] - d[i+1] <= 0
    // d[i] <= d[i+1] + 0
    for (int i = 1; i < N; i++) {
        edges[idx++] = Edge{i+1, i, 0};
    }

    V = N + 1;
    E = idx;

    printf("%d\n", solve());

    return 0;
}
@henrybear327
Copy link

WOW your code didn't satisfy the constraint "The cows are standing in the same order as they are numbered" but still passed! Looks like this isn't tested in the POJ test case.

@amoshyc
Copy link
Author

amoshyc commented May 11, 2016

Thanks! I didn't notice that.
Code has been fixed.

@wenxingxing
Copy link

I think you need to relax all edges from i + 1 to i as well.

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