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;
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; }
|