poj3169 差分约束+spfa

题目链接在这里

题目大意是有N头牛,有的牛喜欢相互挨得近一点,有的想相互离得远一点。输入的第一行给出三个数N, ML, MD,分别代表N头牛,有ML条数据是离得近一点,MD条数据是离得远一点。接下来有ML + MD条数据,每条数据有a b c三个数,代表牛a和牛b离得不超过(或者最少是)c。问第一头牛和第二头牛最远能隔多少。

这是一个差分约束题目,我们分析一下。

假设a是编号比较小的牛,即a < b。那么如果两条牛想挨得近一点的话,应该满足b - a <= c,即有一条点a指向点b且权值为c的边。如果是两条牛想挨得比较远一点的话,就要满足b - a >= c,换算一下就是a - b <= -c,即有一条b指向a且权值为-c的边。然后构建边,用spfa寻找最短路就行了。

代码如下:

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;

const int MaxN = 1010;
const int MaxM = 20010;
const int INF = 0x3f3f3f3f;
int n, ml, md;
int cnt[MaxN], dis[MaxN];
struct Edge{
    int v, w, nxt;
}edge[MaxM];
int head[MaxN], tol;

void addEdge(int u, int v, int c){
    edge[tol].v = v;
    edge[tol].w = c;
    edge[tol].nxt = head[u];
    head[u] = tol++;
}

int spfa(int st){
    memset(dis, INF, sizeof(dis));
    memset(cnt, 0, sizeof(cnt));
    dis[st] = 0;
    cnt[st] = 1;
    priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > que;
    que.push(make_pair(0, st));
    while(!que.empty()){
        pair<int, int> p = que.top();
        que.pop();
        if(p.first != dis[p.second]) continue;
        for(int i = head[p.second]; i != -1; i = edge[i].nxt){
            int v = edge[i].v;
            if(dis[v] > dis[p.second] + edge[i].w){
                dis[v] = dis[p.second] + edge[i].w;
                que.push(make_pair(dis[v], v));
                if(++cnt[v] > n)    return 0;
            }
        }
    }
    return 1;
}

int main(){
    while(~scanf("%d %d %d", &n, &ml, &md)){
        memset(head, -1, sizeof(head));
        tol = 0;
        int a, b, c;
        while(ml--){
            scanf("%d %d %d", &a, &b, &c);
            if(a > b)   swap(a, b);
            addEdge(a, b, c);   //满足b - a <= c, 是一个由a指向b的边
        }
        while(md--){
            scanf("%d %d %d", &a, &b, &c);
            if(a < b)   swap(a, b);
            addEdge(a, b, -c);  //满足大 - 小 >= c --> 小 - 大 <= -c, 大边指向小边
        }
        if(!spfa(1))    printf("-1\n");
        else{
            if(dis[n] == INF)   printf("-2\n");
            else
                printf("%d\n", dis[n]);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Never__Give_Up_/article/details/84504105