思路:
由题意得求差分约束最大值,用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;
}