• P1993 小 K 的农场


    Portal.

    差分约束

    发现题中每个农场的作物数 x i x_i xi 要满足以下约束关系:
    { x a − x b ≥ c 1 x a − x b ≤ c 2 x a = x b {xaxbc1xaxbc2xa=xb

    xaxbc1xaxbc2xa=xb
    把以上关系进行转化,重点是“相等”这一约束关系的转化:
    { x a − x b ≥ c 1 x b − x a ≥ − c 2 x b − x a ≥ 0 x a − x b ≥ 0 {xaxbc1xbxac2xbxa0xaxb0
    xaxbc1xbxac2xbxa0xaxb0

    按照上述约束关系,SPFA 求最长路即可。注意此时 dis 要赋值为 − inf ⁡ -\inf inf

    注意若图不连通,可能会出现有 x i x_i xi 值为 − inf ⁡ -\inf inf 的情况,所以要建立超级源点。

    #include 
    using namespace std;
    
    const int maxn=5005,maxm=1e4+5;
    int head[maxn],cnt,tot[maxn],dis[maxn],n,m;
    bool vis[maxn];
    struct edge{int to,nxt,w;}e[maxm];
    
    void add(int x,int y,int z){e[++cnt]={y,head[x],z},head[x]=cnt;}
    
    bool spfa(int s)
    {
        queue<int> q;
        memset(dis,-0x3f3f3f,sizeof dis);
        dis[s]=0,q.push(s),vis[s]=1,tot[s]++;
        while(!q.empty())
        {
            int x=q.front();q.pop(),vis[x]=0;
            for(int i=head[x];i;i=e[i].nxt)
                if(dis[e[i].to]<dis[x]+e[i].w)
                {
                    dis[e[i].to]=dis[x]+e[i].w;
                    if(!vis[e[i].to]) vis[e[i].to]=1,q.push(e[i].to),tot[e[i].to]++;
                    if(tot[e[i].to]>=n) return 0;
                }
        }
        return 1;
    }
    
    int main()
    {
        cin>>n>>m;
        for(int i=1;i<=m;i++)
        {
            int op;cin>>op;
            if(op==1)
            {
                int a,b,c;cin>>a>>b>>c;
                add(b,a,c);
            }
            else if(op==2)
            {
                int a,b,c;cin>>a>>b>>c;
                add(a,b,-c);
            }
            else
            {
                int a,b;cin>>a>>b;
                add(a,b,0),add(b,a,0);
            }
        }
        for(int i=1;i<=n;i++) add(0,i,0);
        if(spfa(1)) cout<<"Yes";
        else cout<<"No";
        return 0;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
  • 相关阅读:
    扩容ASM共享存储
    Tesla_T4加速卡详细参数
    算法面试题和答案
    不同大小的缓冲区对 MD5 计算速度的影响
    CancerLLM: 癌症领域的大型语言模型
    结构体和联合体
    【ML特征工程】第 1 章 :机器学习管道
    Python-对象与json互转-json读写-文件读写
    【C++】泛型算法(六)Map和Set的使用
    红黑树是怎么来的
  • 原文地址:https://blog.csdn.net/ncwzdlsd/article/details/134252800