差分制約-------------キューイングレイアウト

給餌を待っているとき、牛は友達の近くに立ちたがります。農夫ジョンはNNを持っています

11から番号が付けられた牛

NNへ

、給餌を待っている直線に立っています。ラインの牛乳ステーキの順番は、それらの数と同じです。牛はかなり細いので、同じ姿勢で2頭以上の牛が立っている場合があります。数軸に立っている牛を想像すると、2頭以上の牛が同じ横座標を持つことができます。いくつかの牛はお互いに良い意見を持っています、彼らは2つの間の距離が与えられた数を超えないようにしたいですLL

一方、一部の牛はお互いに非常に嫌悪感を抱いており、2頭の間の距離が所定の数以上であることを望んでいますDD

与えられたMLML

2頭の牛、そしてMDMDについての良い説明

2頭の牛の厄介な説明。あなたの仕事は:要件を満たすソリューションがない場合は-1を出力し、11の場合

牛とNN

乳牛間の距離は任意に大きくでき、出力は-2になります。それ以外の場合は、すべての要件が満たされていると計算されます11

牛とNN

牛間の可能な最大距離。入力フォーマットの最初の行には、3つの整数N、ML、MDN、ML、MDが含まれています

次のMLML

行、各行には3つの正の整数A、B、LA、B、Lが含まれます

、牛AAを示す

牛BB付き

最大LL離れている

距離。次にMDMD

行、各行には3つの正の整数A、B、DA、B、Dが含まれます

、牛AAを示す

牛BB付き

少なくともDD離れている

距離。出力フォーマットは整数を出力し、要件を満たすソリューションがない場合は-1を出力し、11の場合

牛とNN

乳牛間の距離は任意に大きくでき、出力は-2になります。それ以外の場合、出力はすべての要件を満たします11

牛とNN

牛間の可能な最大距離。データ範囲2≤N≤10002≤N≤1000


1≤ML、MD≤1041≤ML、MD≤104


1≤L、D≤1061≤L、D≤106

入力例:4 2 1
1 3 10
2 4 20
2 3 3
出力例:27

#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;
}
公開された元の記事164件 いいね112 訪問者6764

おすすめ

転載: blog.csdn.net/qq_45772483/article/details/105500390