POJ-3169___Layout——差分约束 + 负环

题目链接:点我啊╭(╯^╰)╮

题目大意:

     n n 头牛、按编号排队, M L ML 对牛的距离不能超过 D D M D MD 对牛的距离不能小于 D D ,问 1 1 号牛到 n n 号牛的距离最大是多少???

解题思路:

    差分约束思想,下面简单介绍一下:
X 1 X 2 K 1 X_1 - X_2 ≤ K_1
X 2 X 3 K 2 X_2 - X_3 ≤ K_2
X 1 X 3 K 3 X_1 - X_3 ≤ K_3
那么、不等式 相加得到:
X 1 X 3 K 1 + K 2 X_1 - X_3 ≤ K_1 + K_2
X 1 X 3 K 3 X_1 - X_3 ≤ K_3
要求 X 1 X_1 X 3 X_3 的最大差值,就是 m i n K 1 + K 2 , K 3 min(K_1 + K_2, K_3) ,也就转化为了最短路的思想
同样,若给出 X 1 X 2 K 1 X_1 - X_2 ≥ K_1 ,则转换为 X 2 X 1 K 1 X_2 - X_1 ≤ -K_1 , 一个道理

代码思路:

    判断一下负环即可

核心:差分约束的思想

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int MAXN = 1010;
const int MAXM = 20010;
const int ANS_MAX = 1<<30;

struct EDGE {
	int next;
	int to;
	ll w;
} edge[MAXM];

int n, m, st, cnt;
int head[MAXN], num[MAXN];
ll dis[MAXN];
bool vis[MAXN];
queue<int> Q;

inline int Read() {  //读入优化 可忽略
	char c;
	int ans = 0;
	bool Sign = false;
	while(!isdigit(c=getchar()) && c != '-');
	if(c == '-') {
		Sign = true;
		c = getchar();
	}
	do {
		ans = (ans<<3) + (ans<<1) + (c - '0');
	} while(isdigit(c=getchar()));
	return Sign ? -ans : ans;
}

void Add(int u, int v, ll w) {
	edge[++cnt].next = head[u];
	edge[cnt].to = v;
	edge[cnt].w = w;
	head[u] = cnt;
}

void read() {
	int x, y, ml, md;
	ll w;
	n = Read();
	ml = Read();
	md = Read();
	for(int i=1; i<=ml; i++) {
		x = Read();
		y = Read();
		w = Read();
		Add(x, y, w);
	}
	for(int i=1; i<=md; i++) {
		x = Read();
		y = Read();
		w = Read();
		Add(y, x, -w);
	}
}

bool SPFA(int x) {
	while(!Q.empty()) Q.pop();
	for(int i=1; i<=n; i++) dis[i] = ANS_MAX;
	dis[x] = 0;
	num[x] = 1;
	Q.push(x);
	vis[x] = true;
	while(!Q.empty()) {
		int k = Q.front();
		Q.pop();
		vis[k] = false;
		if(dis[k] == ANS_MAX) continue;
		for(int i=head[k]; i!=0; i=edge[i].next) {
			int j = edge[i].to;
			if(dis[j] > dis[k] + edge[i].w) {
				dis[j] = dis[k] + edge[i].w;
				num[j] = num[k]+1;
				if(num[j]>n) return 1;	//判断负环
				if(!vis[j]) {
					Q.push(j);
					vis[j] = true;
				}
			}
		}
	}
	return 0;
}

int main() {
	memset(vis, 0, sizeof(vis));
	memset(num, 0, sizeof(num));
	memset(head, 0, sizeof(head));
	cnt = 0;
	read();
	if(SPFA(1)) printf("-1\n");
	else if(dis[n]==ANS_MAX) printf("-2\n");
	else printf("%d\n", dis[n]);
}

猜你喜欢

转载自blog.csdn.net/Scar_Halo/article/details/83588771