跳到正文

个人记录

代码

Linda0417约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前
C++
#include<bits/stdc++.h>
using namespace std;
const int N = 100010, M = 2000010;
int n, m;
int price[N];
int h[N], rh[N], e[M], ne[M], idx;
int dmin[N], dmax[N];
bool st[N];
void add(int *h, int a, int b) {
	e[idx] = b;
	ne[idx] = h[a];
	h[a] = idx++;
}
void spfa(int *d, int start, int *h, bool flag) {
	queue<int> q;
	memset(st, 0, sizeof(st));
	if(flag) memset(d, 0x3f, sizeof(dmin));
	q.push(start);
	st[start] = 1;
	d[start] = price[start];
	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(flag && d[j] > min(d[t], price[j]) || !flag && d[j] < max(d[t], price[j])) {
				if(flag) d[j] = min(d[t], price[j]);
				else d[j] = max(d[t], price[j]);
				if(!st[j]) {
					st[j] = 1;
					q.push(j);
				}
			}
		}
	}
}
int main() {
	scanf("%d %d", &n, &m);
	memset(h, -1, sizeof(h));
	memset(rh, -1, sizeof(rh));
	for(int i = 1; i <= n; i++) scanf("%d", &price[i]);
	while(m--) {
		int a, b, c;
		scanf("%d %d %d", &a, &b, &c);
		add(h, a, b);
		add(rh, b, a);
		if(c == 2) {
			add(h, b, a);
			add(rh, a, b);
		}
	}
	spfa(dmin, 1, h, 1);
	spfa(dmax, n, rh, 0);
	int res = 0;
	for(int i = 1; i <= n; i++) res = max(res, dmax[i] - dmin[i]);
	printf("%d\n", res);
	return 0;
}
原文