POJ 3169 Layout (差分约束)

题目链接

思路:
由题意得求差分约束最大值,用spfa求最短路。
建图:
对于喜欢的人dis[r] - dis[l] <= w,直接建l -> r权值为w的边;
对于不喜欢的人dis[r] - dis[l] >= w化为dis[l] - dis[r] <= -w,则建r -> l边权为-w的边;
求最短路dis[n]等于INF时说明n点不可达,就代表n点没约束到位置就可以任意值返回 -2,
当图中存在环的话永远无法求出最短路,则答案不存在返回-1,
无环且dis[n]可达则返回dis[n]。

代码:

#include <iostream>
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <math.h>
#include <climits>
#include <iomanip>
#include <queue>
#include <vector>
#define fastio ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL)
#define debug(a) cout << "debug : " << (#a) << " = " << a << endl

using namespace std;

typedef long long ll;
typedef pair<int, int> PII;

const int N = 1010, M = 2e4 + 10;
const int INF = 0x3f3f3f3f;
const double eps = 1e-6;
const int mod = 998244353;

int dis[N], cnt[N];
bool vis[N];
int n, ml, md;

int h[N], idx;
struct node
{
    int r, w, nt;
} a[M];
void add(int l, int r, int w)
{
    a[idx] = {r, w, h[l]}, h[l] = idx++;
}

int spfa()
{
    memset(dis, INF, sizeof dis);
    memset(cnt, 0, sizeof cnt);
    dis[1] = 0;
    queue<int> q;
    q.push(1);
    cnt[1] = 1;
    vis[1] = true;
    while (q.size())
    {
        int t = q.front();
        q.pop();
        vis[t] = false;
        for (int i = h[t]; i != -1; i = a[i].nt)
        {
            int j = a[i].r, w = a[i].w;
            if (dis[j] > dis[t] + w) //求最长路
            {
                dis[j] = dis[t] + w;
                cnt[j] = cnt[t] + 1;
                if (cnt[j] > n)
                    return -1;
                if (!vis[j])
                {
                    q.push(j);
                    vis[j] = true;
                }
            }
        }
    }
    return dis[n] == INF ? -2 : dis[n];
}

int main()
{
    memset(h, -1, sizeof h);
    cin >> n >> ml >> md;
    while (ml--)
    {
        int l, r, w;
        scanf("%d%d%d", &l, &r, &w);
        add(l, r, w);
    }
    while (md--)
    {
        int l, r, w;
        scanf("%d%d%d", &r, &l, &w); //反边
        add(l, r, -w);
    }
    cout << spfa() << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值