341. 最优贸易

思路

我们需要找到一个路径上的最大解

我们可以分为n个分界点, 在k之前的最小价格和在k之后的最大价格

再用k之后的最大价格减去k之前的最小价格就是我们要求的的最终解

正向遍历一遍,再反向遍历一遍. 所以我们需要两个相反的领接表来存储边的信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N = 100010;
const int M = 2000010;

// 使用两个不同的领接表来存储信息
int ht[N], hs[N], e[M], ne[M], idx;

// 以k为分界点, 分别存储k左右的最大值和最小值
int dmax[N], dmin[N];
int st[N];
int q[M];
int n, m;
int w[N];

void add(int* h, int a, int b)
{
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}

// 分两种情况, 从起点开始遍历和从终点开始遍历
void spfa(int* h, int* dist, int flag)
{
int hh = 0, tt = 0;
memset(st, 0, sizeof st);
if(flag)
{
memset(dist, -0x3f, sizeof dmax);
dist[n] = w[n];
st[n] = 1;
q[tt++] = n;
}
else
{
memset(dist, 0x3f, sizeof dmin);
dist[1] = w[1];
st[1] = 1;
q[tt++] = 1;
}

while(hh != tt)
{
int t = q[hh++];
st[t] = 0;
if(hh == M) hh = 0;

for(int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
// 判断当前点是否是最小值或最大值
if( ( !flag && dist[j] > min(dist[t], w[j]) )||(flag && dist[j] < max(dist[t], w[j]) ) )
{
if(!flag) dist[j] = min(dist[t], w[j]);
else dist[j] = max(dist[t], w[j]);

// 入队
if(!st[j])
{
q[tt++] = j;
if(tt == M) tt = 0;
st[j] = 1;
}
}
}
}
}

int main()
{
memset(ht, -1, sizeof ht);
memset(hs, -1, sizeof hs);
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> w[i];

for(int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(ht,b,a);
add(hs,a,b);

if(c == 2)
{
add(ht,a,b);
add(hs,b,a);
}
}

spfa(hs,dmin,0);
spfa(ht,dmax,1);

// 从头到尾遍历一遍所有的分界点, 判断最大值
int ans = 0;
for(int i = 1; i <= n ; i++)
{
ans = max(ans,dmax[i] - dmin[i]);
}

cout << ans;
return 0;
}