POJ - 3159(Candies)差分约束

题意:

就是分糖果 然后A觉得B比他优秀  所以分的糖果可以比他多 但最多不能超过c1个, B又觉得A比他优秀。。。。

符合差分约束的条件  

设A分了x个  B分了y个  则x-y <= c1 , 根据其它的关系可以找出c2 c3 ····

如果不懂差分约束的请  点击

所以构成不等式组:x-y <= c1   x-y <= c2    x-y <=c3

因为这些条件要都符合 所以取最小的c  即最短路

#include <iostream>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <queue>
#include <stack>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn = 1000010, INF = 0x7fffffff;
typedef long long LL;
int head[maxn], d[maxn], vis[maxn];
int n, m;
struct node{
    int u,v,w,next;
}Node[maxn];

void add(int u,int v,int w,int i)
{
    Node[i].u = u;
    Node[i].v = v;
    Node[i].w = w;
    Node[i].next = head[u];
    head[u] = i;
}

void spfa(int s)
{
    stack<int> Q;
    for(int i=0; i<=n; i++) d[i] = INF;
    d[s] = 0;
    mem(vis,0);
    Q.push(s);
    vis[s] = 1;
    while(!Q.empty())
    {
        int x = Q.top(); Q.pop();
        vis[x] = 0;
        for(int i=head[x]; i!=-1; i=Node[i].next)
        {
            node e = Node[i];
            if(d[e.v] > d[x] + e.w)
            {
                d[e.v] = d[x] + e.w;
                if(!vis[e.v])
                {
                    Q.push(e.v);
                    vis[e.v] = 1;
                }
            }
        }
    }
}
int main()
{
    scanf("%d%d",&n,&m);
    mem(head,-1);
    for(int i=0; i<m; i++)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        add(u,v,w,i);
    }

    spfa(1);
    printf("%d\n",d[n]);

    return 0;
}

猜你喜欢

转载自www.cnblogs.com/WTSRUVF/p/9157715.html
今日推荐