P1993 小K的农场

差分约束的模版题,建图我们选择 a b c 代表 v(b) - v(a) <= -c 建图,然后注意到在区间 [ i , i + 1] 里面,有 v(i + 1) - v(i) <= 1

且 v(i) - v(i + 1) <= 0,这样建图,可以保证整张图的联通性,然后spfa跑图上最短路(有负权边),如果存在负环,则方程无解,否则若存在最短路,则必定有解,据说递归spfa跑负环特别快(逃。

代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int,int> Pi;
typedef unsigned long long ULL;
int gcd(int a,int b){if (b == 0) return a; return gcd(b , a%b);}
int lcm(int a, int b){ return a/gcd(a,b)*b;}
inline int read(){
    int f = 1, x = 0;char ch = getchar();
    while (ch > '9' || ch < '0'){if (ch == '-')f = -f;ch = getchar();}
    while (ch >= '0' && ch <= '9'){x = x * 10 + ch - '0';ch = getchar();}
    return x * f;
}
const int maxn = 1e5 + 10;
int n,m,tot;
int head[maxn],dis[maxn],vis[maxn],cnt[maxn];
int q[maxn*10],l,r;
struct _edge {
    int to,nex,w;
}edge[maxn];
void add(int u,int v,int w){
    edge[tot].to = v;
    edge[tot].w = w;
    edge[tot].nex = head[u];
    head[u] = tot++;
}
int _spfa(int u){
    vis[u] = 1;
    for (int i=head[u]; ~i; i = edge[i].nex) {
        int v = edge[i].to;
        if (dis[v] > dis[u] + edge[i].w){
            dis[v] = dis[u] + edge[i].w;
            if (vis[v]) return 0;
            if (!_spfa(v)) return 0;
        }
    }
    vis[u] = 0;
    return 1;
}
int main(){
   // freopen("/Users/chutong/data.txt", "r", stdin);
    n = read(); m = read();
    memset(head, -1, sizeof(head));
    for (int i=1; i<=m; i++) {
        int tag = read();
        if (tag == 1){
            int a = read(),b = read(),c = read();
            add(b, a, -c);
        }else if (tag == 2){
            int a = read(),b = read(),c = read();
            add(a, b, c);
        }else if (tag == 3){
            int a = read(),b = read();
            add(a, b, 0); add(b, a, 0);
        }
    }
    for (int i=1; i<=n; i++)
        add(0, i, 0);
    for (int i=1; i<=n; i++)
        dis[i] = INT_MAX;
    if (!_spfa(0)) puts("No");
    else puts("Yes");
    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值