【bzoj】3436 小k的农场 差分约束

今天上午刚讲了差分约束,这个是练习题。
就是个比较明显【luo】的差分约束+SPFA判负环
注意spfa判负环的过程和怎么建边就可以了
我是神奇的传送门

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
int tot;
int n,m;
const int maxn=100000+15;
int head[maxn],next[maxn<<1],d[maxn];
bool used[maxn];
struct haha
{
    int f,t,cost;
}es[maxn<<1];
void init()
{
    memset(head,-1,sizeof(head));
    tot=0;
}
void build(int ff,int tt,int dd)
{
    es[++tot]=(haha){ff,tt,dd};
    next[tot]=head[ff];
    head[ff]=tot;
}
queue<int>q;
bool flag;
int tim[maxn];
bool done[maxn];
void spfa(int s)
{
    memset(d,0x3f,sizeof(d));
    d[s]=0;
    q.push(s);
    used[s]=1;
    tim[s] = 0;
    done[s] = true;
    while(!q.empty())
    {
        int u=q.front();
        q.pop();
        used[u]=0;
        done[u] = true;
        for(int i=head[u];i != -1;i=next[i])
        {
            int v=es[i].t;
            if(d[v]>d[u]+es[i].cost)
            {
                d[v]=d[u]+es[i].cost;
                if(!used[v])
                {
                    q.push(v);
                    used[v]=1;
                }
                tim[v] = tim[u] + 1;
                if(tim[v] > n + 1)
                {
                    flag=1;
                    return;
                }
            }
        }
    }
}
int main()
{
    int a,b,c;
    int t;
    scanf("%d%d",&n,&m);
    init();
    for(int i=1;i<=m;i++)
    {
        scanf("%d",&t);
        if(t==1)
        {
            scanf("%d%d%d",&a,&b,&c);
            build(a,b,-c);
        }
        else if(t==2)
        {
            scanf("%d%d%d",&a,&b,&c);
            build(b,a,c);
        }
        else if(t==3)
        {
            scanf("%d%d",&a,&b);
            build(b,a,0);
            build(a,b,0);
        }
    }
    for(int i=1;i<=n;i++)
    {
        if(!done[i])
            spfa(i);
        if(flag)
        {
            puts("No");
            return 0;
        }
    }
    puts("Yes");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值