#include<bits/stdc++.h> using namespace std; const int maxn=1e5+100; struct node { int u,v,nxt; }edge[maxn*10],edge2[maxn*10]; int head[maxn],head2[maxn]; int tot=0,tot2=0; void addedge (int u,int v) { edge[tot].u=u; edge[tot].v=v; edge[tot].nxt=head[u]; head[u]=tot++; } void addedge2 (int u,int v) { edge2[tot2].u=u; edge2[tot2].v=v; edge2[tot2].nxt=head2[u]; head2[u]=tot2++; } int w[maxn],n,m; int visit[maxn],visit2[maxn]; int d[maxn];//表示从1出发到当前节点所能达到的最小权值 int d2[maxn];//表示从当前节点出发到n所能达到的最大权值 struct qnode { int v,w; bool operator < (const qnode &r) const { return w>r.w; } }; void dijkstra (int s) { priority_queue<qnode> q; q.push({s,w[s]}); d[s]=w[s]; visit[s]=1; while (!q.empty()) { qnode u=q.top(); q.pop(); for (int i=head[u.v];i!=-1;i=edge[i].nxt) { int v=edge[i].v; d[v]=min(min(w[v],d[v]),d[u.v]); if (!visit[v]) q.push({v,d[v]}),visit[v]=1; } } } void dijkstra2 (int s) { priority_queue<qnode> q; q.push({s,-w[s]}); d2[s]=w[s]; visit2[s]=1; while (!q.empty()) { qnode u=q.top(); q.pop(); for (int i=head2[u.v];i!=-1;i=edge2[i].nxt) { int v=edge2[i].v; d2[v]=max(max(w[v],d2[v]),d2[u.v]); if (!visit2[v]) q.push({v,-d2[v]}),visit2[v]=1; } } } int main () { scanf("%d%d",&n,&m); for (int i=1;i<=n;i++) scanf("%d",&w[i]),head[i]=-1,head2[i]=-1,d[i]=1e9,d2[i]=0; for (int i=0;i<m;i++) { int x,y,f; scanf("%d%d%d",&x,&y,&f); addedge(x,y); if (f==2) addedge(y,x); addedge2(y,x); if (f==2) addedge2(x,y); } dijkstra(1); dijkstra2(n); int Max=0; for (int i=1;i<=n;i++) { //printf("%d %d %d %d %d\n",i,d[i],d2[i],visit[i],visit2[i]); Max=max(Max,d2[i]-d[i]); } printf("%d\n",Max); return 0; }
原文:https://www.cnblogs.com/zhanglichen/p/13448511.html