codevs2404糖果

題目描述 Description
幼兒園裏有N個小朋友,lxhgww老師現在想要給這些小朋友們分配糖果,要求每個小朋友都要分到糖果。但是小朋友們也有嫉妒心,總是會提出一些要求,比如小明不希望小紅分到的糖果比他的多,於是在分配糖果的時候,lxhgww需要滿足小朋友們的K個要求。幼兒園的糖果總是有限的,lxhgww想知道他至少需要準備多少個糖果,才能使得每個小朋友都能夠分到糖果,並且滿足小朋友們所有的要求。

輸入描述 Input Description
輸入的第一行是兩個整數N,K。
接下來K行,表示這些點需要滿足的關係,每行3個數字,X,A,B。
如果X=1, 表示第A個小朋友分到的糖果必須和第B個小朋友分到的糖果一樣多;
如果X=2, 表示第A個小朋友分到的糖果必須少於第B個小朋友分到的糖果;
如果X=3, 表示第A個小朋友分到的糖果必須不少於第B個小朋友分到的糖果;
如果X=4, 表示第A個小朋友分到的糖果必須多於第B個小朋友分到的糖果;
如果X=5, 表示第A個小朋友分到的糖果必須不多於第B個小朋友分到的糖果;

輸出描述 Output Description
輸出一行,表示lxhgww老師至少需要準備的糖果數,如果不能滿足小朋友們的所有要求,就輸出-1

樣例輸入 Sample Input
5 7
1 1 2
2 3 2
4 4 1
3 4 5
5 4 5
2 3 5
4 5 1
樣例輸出 Sample Output
11
數據範圍及提示 Data Size & Hint
對於30%的數據,保證 N<=100
對於100%的數據,保證 N<=100000
對於所有的數據,保證 K<=100000,1<=X<=5,1<=A, B<=N
差分約束系統:
1、a = b:建雙向邊,權值爲0
2、a < b :b-a >= 1—>b>=a+1;建a到b 權值爲1的邊
3、a >= b : a >= b+0 建b到a權值爲0的邊
4、a > b:a-b >= 1—->a >= b+1;建b到a權值爲1的邊
5、a <= b:建a到b權值爲0的邊
跑一遍最長路

#include <cstdio>
#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
const int MAXN = 200000;
int head[MAXN],nxt[MAXN<<1],tim[MAXN],tot,n,m;
long long dis[MAXN];
bool vis[MAXN],flag = 0;
struct Edge
{
    int from,to,cost;
}edge[MAXN<<1];
void build(int f,int t,int d)
{
    edge[++tot].from = f;
    edge[tot].to = t;
    edge[tot].cost = d;
    nxt[tot] = head[f];
    head[f] = tot;
}
deque <int>q;
void spfa(int s)
{
    memset(dis,-1,sizeof(dis));
    dis[s] = 0;
    vis[s] = 1;tim[0]=1;
    q.push_front(s);
    while(!q.empty())
    {
        int x = q.front();
        q.pop_front();
        vis[x] = 0;
        for(int i = head[x]; i ; i = nxt[i])
        {
            Edge e = edge[i];
            if(dis[e.to] < dis[x]+e.cost)
            {
                dis[e.to] = dis[x]+e.cost;
                if(++tim[e.to] > n)
                {
                    flag = 1;
                    return ;
                }
                if(!vis[e.to])
                {
                    if(q.empty())
                    q.push_back(e.to );
                    else if(dis[q.front()] < dis[e.to])
                    q.push_front(e.to );
                    else
                    q.push_back(e.to);
                    vis[e.to] = 1;
                }
            }
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    int t,a,b;
    for(int i = 1; i <= m; i ++)
    {
        scanf("%d%d%d",&t,&a,&b);
        if(t == 1)build(a,b,0),build(b,a,0);
        else if(t == 2)
        {
            build(a,b,1);
        }
        else if(t == 3)
        build(b,a,0);
        else if(t == 4)
        build(b,a,1);
        else if(t == 5)
        build(a,b,0);
    }
    for(int i = n; i >= 1; i --)
    build(0,i,1);
    spfa(0);
    if(flag)
    puts("-1");
    else
    {
        long long ans = 0;
        for(int i = 1; i <= n; i ++)
        ans += dis[i];
        printf("%lld\n",ans);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章