图论--差分约束模板

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define INF 1e9
using namespace std;
const int maxn=1000+10;
const int maxm=50000+10;
 
struct Edge
{
    int from,to,dist;
    Edge(){}
    Edge(int f,int t,int d):from(f),to(t),dist(d){}
};
 
struct BellmanFord
{
    int n,m;
    int head[maxn],next[maxm];
    Edge edges[maxm];
    bool inq[maxn];
    int cnt[maxn];
    int d[maxn];
 
    void init(int n)
    {
        this->n=n;
        m=0;
        memset(head,-1,sizeof(head));
    }
 
    void AddEdge(int from,int to,int dist)
    {
        edges[m]=Edge(from,to,dist);
        next[m]=head[from];
        head[from]=m++;
    }
 
    int bellmanford(int s)
    {
        memset(inq,0,sizeof(inq));
        memset(cnt,0,sizeof(cnt));
        queue<int> Q;
        for(int i=1;i<=n;i++) d[i]= i==s?0:INF;
        Q.push(s);
 
        while(!Q.empty())
        {
            int u=Q.front(); Q.pop();
            inq[u]=false;
            for(int i=head[u];i!=-1;i=next[i])
            {
                Edge &e=edges[i];
                if(d[e.to] > d[u]+e.dist)
                {
                    d[e.to] = d[u]+e.dist;
                    if(!inq[e.to])
                    {
                        inq[e.to]=true;
                        Q.push(e.to);
                        if(++cnt[e.to]>n) return -1;
                    }
                }
            }
        }
        return d[n]==INF?-2:d[n];
    }
}BF;
 
int main()
{
    int n,m;
    while(scanf("%d%d",&n,&m)==2)
    {
        BF.init(n);
        while(m--)
        {
            int u,v,d;
            scanf("%d%d%d",&u,&v,&d);//转化为a-b<=val a向b连权值为val的边 
            BF.AddEdge(u,v,d);
        }
        for(int i=1;i<=n;i++)
           BF.AddEdge(0,i,0); //保证图的连通性
                //注意特殊关系
        if(BF.bellmanford(0)!=-1) printf("%d\n",BF.bellmanford(1));
        else puts("-1");
    }
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值