poj3169 差分约束+spfa

该博客讨论了POJ3169题目,涉及N头牛的喜好距离问题。通过建立差分约束模型,利用SPFA算法求解两头牛之间可能的最大距离。文章解释了如何根据牛之间的亲近或远离关系构建边,并提供了相应的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接在这里

题目大意是有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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值