P1073 最优贸易
#include <bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int head1[maxn], head2[maxn], maxx[maxn], minn[maxn];
bool in1[maxn], in2[maxn];
int value[maxn];
int N, m, s;
struct edge
{
int to, next;
}es1[maxn], es2[maxn];
queue<int> q;
int num1 = 0, num2 = 0;
void link(int x, int y) {
num1++;
es1[num1].to = y;
es1[num1].next = head1[x];
head1[x] = num1;
num2++;
es2[num2].to = x;
es2[num2].next = head2[x];
head2[y] = num2;
}
void spfa1() {
memset(minn, 127, sizeof(minn));
minn[s] = value[s];
in1[s] = 1;
q.push(s);
while(!q.empty()) {
int x = q.front();
q.pop();
in1[x] =false;
for(int i = head1[x]; i != -1; i = es1[i].next) {
int n = es1[i].to;
if(minn[n] > minn[x] || value[n] < minn[n]) {
minn[n] = min(minn[x], value[n]);
if(in1[n] == 0) {
q.push(n);
in1[n] = true;
}
}
}
}
}
void spfa2() {
memset(maxx, -1, sizeof(maxx));
maxx[N] = value[N];
in2[N] = 1;
q.push(N);
while(!q.empty()) {
int x = q.front();
q.pop();
in2[x] =false;
for(int i = head2[x]; i != -1; i = es2[i].next) {
int n = es2[i].to;
if(maxx[n] < maxx[x] || value[n] > maxx[n]) {
maxx[n] = max(maxx[x], value[n]);
if(in2[n] == 0) {
q.push(n);
in2[n] = true;
}
}
}
}
}
int main() {
// freopen("input.in", "r", stdin);
memset(head1, -1, sizeof(head1));
memset(head2, -1, sizeof(head2));
memset(in1, 0, sizeof(in1));memset(in2, 0, sizeof(in2));
cin >> N >> m;
s = 1;
for(int i = 1; i <= N; i++) cin >> value[i];
for(int i = 1; i <= m; i++) {
int x, y, z;
cin >> x >> y >> z;
link(x, y);
if(z == 2) link(y, x);
}
spfa1();
spfa2();
int ans = 0;
for(int i = 1; i <= N; i++) {
ans = max(maxx[i]-minn[i], ans);
}
cout << ans;
}
明白了一个道理:spfa不仅仅能求最短路啊!
以后要记住,如果要求求一条路上的某个值,可以考虑用spfa