S - Layout(SPFA + 差分约束)

大致题意 : 有n个小朋友, 给定一些条件,条件分为两种 :

第一种是A,B不超过一定距离

第二种是A,B不小于一定距离

通过这些条件给他们排列, 问1到n的最远距离.

思路 : 由条件可以通过差分约束系统转化为最短路有关问题(这里是求最远路)

第一类条件是 a-b<d可转化为d[a]<d[b]+d(注意是最远路的松弛操作)

第二类条件是a-b>d可转化为 d[b]<d[a] + (-d)

通过这两个转化建图, 用SPFA求最短路, 若出现负环则不能排列返回-1.

AC代码如下:

#include <iostream>
#include <cstring>
#include <cstdio>
#include <string>
#include <iterator>
#include <cmath>
#include <algorithm>
#include <sstream>
#include <map>
#include <stack>
#include <set>
#include <queue>
#include <iomanip>
using namespace std;

stringstream ss;
typedef long long ll;
typedef pair<int, int> PII;
const int N = 1010, M = 1e5+10;
const int INF = 0x3f3f3f3f;

int n,ml,md;
int h[N],e[M],ne[M],w[M],idx;
int d[N],cnt[N];
bool st[N];

void add(int a, int b, int c)
{
    e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx++;
}

int SPFA()
{
    queue<int> q;
    q.push(1);
    st[1] = 1;
    d[1] = 0;
    while(q.size())
    {
        int t = q.front();
        q.pop();

        st[t] = 0;

        for(int i = h[t]; ~i; i = ne[i])
        {
            int j = e[i];
            if(d[j] > d[t] + w[i])
            {
                d[j] = d[t] + w[i];
                cnt[j] = cnt[t] + 1;
                if(cnt[j] >= n) return -1;
                if(!st[j])
                {
                    q.push(j);
                    st[j] = 1;
                }
            }
        }
    }

    if(d[n] == INF) return -2;
    else return d[n];
}
int main()
{
    cin>>n>>ml>>md;

    memset(h, -1, sizeof h);
    memset(d, 0x3f, sizeof d);
    
    while(ml -- )
    {
        int a,b,c;
        cin>>a>>b>>c;
        add(a,b,c);
    }

    while(md -- )
    {
        int a,b,c;
        cin>>a>>b>>c;
        add(b,a,-c);
    }
    cout<<SPFA();
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值