洛谷 P4878 [USACO05DEC] Layout G

题目大意

n n n 头编号为 1,2,…, n n n 的奶牛,它们按照编号顺序排成一排。有些奶牛是好基友,它们希望彼此之间的距离小于等于某个数。有些奶牛是情敌,它们希望彼此之间的距离大于等于某个数。给出 M L M_L ML 对的基友关系,它们希望距离在某个范围内。给出 M L M_L ML 对的情敌关系,它们希望距离在某个范围外。如果满足上述所有条件,1 号奶牛和 n n n 号奶牛之间的距离最大为多少。

分析

如果是基友关系,则满足 b − a ≤ x b-a\le x bax。如果是情敌关系则满足 c − d ≥ y c-d\ge y cdy。全都转换成小于等于的情形,然后跑最短路即可。

思维点

如果给出两组关系: 4 − 1 ≤ 10 4-1\le10 4110 3 − 2 ≥ 50 3-2\ge 50 3250。则一定产生矛盾。产生的图为:
在这里插入图片描述
这是不可能的。但我们在图中跑最短路,并不会发现这样的矛盾。因为,1 4 顶点与 2 3 顶点在图中表现出来是非连通的。因此,我们漏掉了一些图中顶点的关联信息: 2 − 1 ≥ 0 、 3 − 2 ≥ 0 、 4 − 3 ≥ 0 2-1\ge 0、3-2\ge 0、4-3\ge 0 210320430

示例程序

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

using namespace std;

const int N = 1010, M = 10000 + 10000 + 1000 + 10, INF = 0x3f3f3f3f;

int n, m1, m2;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
int q[N], cnt[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++ ;
}

bool spfa(int size)
{
    int hh = 0, tt = 0;
    memset(dist, 0x3f, sizeof dist);
    memset(st, 0, sizeof st);
    memset(cnt, 0, sizeof cnt);

    for (int i = 1; i <= size; i ++ )
    {
        q[tt ++ ] = i;
        dist[i] = 0;
        st[i] = true;
    }

    while (hh != tt)
    {
        int t = q[hh ++ ];
        if (hh == N) hh = 0;
        st[t] = false;

        for (int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if (dist[j] > dist[t] + w[i])
            {
                dist[j] = dist[t] + w[i];
                cnt[j] = cnt[t] + 1;
                if (cnt[j] >= n) return true;
                if (!st[j])
                {
                    q[tt ++ ] = j;
                    if (tt == N) tt = 0;
                    st[j] = true;
                }
            }
        }
    }

    return false;
}

int main()
{
    scanf("%d%d%d", &n, &m1, &m2);
    memset(h, -1, sizeof h);

    for (int i = 1; i < n; i ++ ) add(i + 1, i, 0);
    while (m1 -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        if (a > b) swap(a, b);
        add(a, b, c);
    }
    while (m2 -- )
    {
        int a, b, c;
        scanf("%d%d%d", &a, &b, &c);
        if (a > b) swap(a, b);
        add(b, a, -c);
    }

    if (spfa(n)) puts("-1");
    else
    {
        spfa(1);
        if (dist[n] == INF) puts("-2");
        else printf("%d\n", dist[n]);
    }

    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值