题目链接
建立正反两张有向图,先以1为起点,在原图上跑SPFA或dijkstra,求出1到x的所有路径中经过权值最小节点的权值D[x];再反向跑一遍,求出最大F[x],然后枚举所有点,用F[x]-D[x]更新答案
我用的dijkstra,不加任何优化会T掉1个点,加了fread读优后洛谷上还是会T,再加O2就AC,在Contest Hunter上过了。
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
typedef long long ll;
const int BUF=40000000;
char Buf[BUF],*buf=Buf;
const int OUT=20000000;
char Out[OUT],*ou=Out;int Outn[30],Outcnt;
inline void write(int x){
if(!x)*ou++=48;
else{
for(Outcnt=0;x;x/=10)Outn[++Outcnt]=x%10+48;
while(Outcnt)*ou++=Outn[Outcnt--];
}
}
inline void writell(ll x){
if(!x)*ou++=48;
else{
for(Outcnt=0;x;x/=10)Outn[++Outcnt]=x%10+48;
while(Outcnt)*ou++=Outn[Outcnt--];
}
}
inline void writechar(char x){*ou++=x;}
inline void writeln(){*ou++='\n';}
inline void read(int&a){for(a=0;*buf<48;buf++);while(*buf>47)a=a*10+*buf++-48;}
#define _rep(i,a,b) for(int i=(a);i<=(b);i++)
typedef pair<int,int> P;
const int N=1e5+10;
const int M=5e5+10;
int n,m;
int price[N];
struct Edge1{
int v,nx;
}edge1[M<<1];
struct Edge2{
int v,nx;
}edge2[M<<1];
int head1[N],tot1,head2[N],tot2;
void addedge1(int u,int v)
{
edge1[tot1].v=v;
edge1[tot1].nx=head1[u];
head1[u]=tot1++;
}
void addedge2(int u,int v)
{
edge2[tot2].v=v;
edge2[tot2].nx=head2[u];
head2[u]=tot2++;
}
struct cmp{
bool operator()(const P p1,const P p2)
{
return p1.second>p2.second;
}
};
priority_queue<P,vector<P>,cmp>q1,q2;
int dis1[N],dis2[N];
bool vis1[N],vis2[N];
void dijkstra1(int s)
{
memset(dis1,0x3f,sizeof(dis1));
memset(vis1,false,sizeof(vis1));
dis1[s]=price[s];
q1.push(make_pair(s,price[s]));
while(!q1.empty())
{
P tmp=q1.top();q1.pop();
int u=tmp.first;
vis1[u]=true;
for(int i=head1[u];~i;i=edge1[i].nx)
{
int v=edge1[i].v;
if(vis1[v])continue;
dis1[v]=min(dis1[u],price[v]);
q1.push(make_pair(v,dis1[v]));
}
}
}
void dijkstra2(int s)
{
memset(dis2,0xff,sizeof(dis2));
memset(vis2,false,sizeof(vis2));
dis2[s]=price[s];
q2.push(make_pair(s,dis2[s]));
while(!q2.empty())
{
P tmp=q2.top();q2.pop();
int u=tmp.first;
vis2[u]=true;
for(int i=head2[u];~i;i=edge2[i].nx)
{
int v=edge2[i].v;
if(vis2[v])continue;
dis2[v]=max(dis2[u],price[v]);
q2.push(make_pair(v,dis2[v]));
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
fread(Buf,1,BUF,stdin);
read(n);read(m);
memset(head1,-1,sizeof(head1));
memset(head2,-1,sizeof(head2));
_rep(i,1,n)read(price[i]);
int x,y,z;
_rep(i,1,m)
{
read(x);read(y);read(z);
if(z==1)
{
addedge1(x,y);
addedge2(y,x);
}
else
{
addedge1(x,y);
addedge1(y,x);
addedge2(x,y);
addedge2(y,x);
}
}
dijkstra1(1);
dijkstra2(n);
int ans=0;
_rep(i,1,n)
ans=max(ans,dis2[i]-dis1[i]);
write(ans);writeln();
fwrite(Out,1,ou-Out,stdout);
return 0;
}