POJ 3169 差分约束系统 + spfa

具体讲解看链接,证明的很清楚,神奇的差分约束系统将不等式和图论中的最短路联系起来,数形结合应用的妙不可言。

http://blog.csdn.net/zhang20072844/article/details/7788672

代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define lson l, m, k << 1
#define rson m, r, k << 1 | 1

using namespace std;

typedef long long int LL;
const int INF = 0x3f3f3f3f;
const int maxn = 1005;
int N, ML, MD;
struct edge{
    int to, dis;
    edge(int a, int b){to = a; dis = b;}
    edge(){}
};
vector G[maxn];

void spfa(){
    int Inque[maxn], d[maxn];
    memset(Inque, 0, sizeof(Inque));
    memset(d, INF, sizeof(d));
    queue Q;
    Q.push(1);
    Inque[1] = 1;
    d[1] = 0;
    while (!Q.empty()){
        int u = Q.front();
        Q.pop();
        Inque[u] = 0;
        for (int i = 0; i < G[u].size(); i++){
            edge e = G[u][i];
            int v = e.to, w = e.dis;
            if (d[v] > d[u] + w){
                d[v] = d[u] + w;
                if (!Inque[v]){
                    Q.push(v);
                    Inque[v] = 1;
                }
                if (d[v] < 0){
                    printf("-1\n");
                    return;
                }
            }
        }
    }
    if (d[N] == INF) printf("-2\n");
    else printf("%d\n", d[N]);
}

int main()
{
    //freopen("1.txt", "r", stdin);
    scanf("%d%d%d", &N, &ML, &MD);

    int u, v, d;//建图
    for (int i = 1; i < N; i++)
        G[i + 1].push_back(edge(i, 0));
    for (int i = 1; i <= ML; i++){
        scanf("%d%d%d", &u, &v, &d);
        G[u].push_back(edge(v, d));
    }
    for (int i = 1; i <= MD; i++){
        scanf("%d%d%d", &u, &v, &d);
        G[v].push_back(edge(u, -d));
    }

    spfa();
    return 0;
}


 

 

你可能感兴趣的:(ACM-差分约束系统)