【NOIP 2009】最优贸易(双向spfa)
** Solution: **
maxn数组用来存储“从终点到某点间的最大卖出价”,而minn数组用来存储“从起点到某点间的最小买入价”。两遍spfa跑完之后枚举每一对maxn与minn找到最大的差值即可
写的时候注意逻辑,思路一定要清晰,不然很久都调不出来
#include<bits/stdc++.h>
#define N 100005
#define M 500005
using namespace std;
int n,m,cost[N],tot1,tot2,first1[N],first2[N];
int min_cost[N],max_cost[N];
bool inque[N];
struct node
{
int to,next,val;
};
node forward[2*M],back[2*M];
inline void addedge_forward(int x,int y,int z)
{
tot1++;
forward[tot1].to=y;
forward[tot1].val=z;
forward[tot1].next=first1[x];
first1[x]=tot1;
}
inline void addedge_back(int x,int y,int z)
{
tot2++;
back[tot2].to=y;
back[tot2].next=first2[x];
back[tot2].val=z;
first2[x]=tot2;
}
queue <int> q;
inline void spfa_forward(int s)
{
memset(min_cost,127,sizeof(min_cost));
inque[s]=true;
q.push(s);
min_cost[s]=cost[s];
while(!q.empty())
{
int now=q.front();
q.pop();
inque[now]=false;
for(int u=first1[now];u;u=forward[u].next)
{
int vis=forward[u].to;
if(min_cost[vis]>min(min_cost[now],forward[u].val))
{
min_cost[vis]=min(min_cost[now],forward[u].val);
if(!inque[vis])
{
inque[vis]=true;
q.push(vis);
}
}
}
}
}
inline void spfa_back(int s)
{
while(q.size()) q.pop();
memset(inque,false,sizeof(inque));
memset(max_cost,128,sizeof(max_cost));
inque[s]=true;
q.push(s);
max_cost[s]=cost[s];
while(!q.empty())
{
int now=q.front();
q.pop();
inque[now]=false;
for(int u=first2[now];u;u=back[u].next)
{
int vis=back[u].to;
if(max_cost[vis]<max(max_cost[now],back[u].val))
{
max_cost[vis]=max(max_cost[now],back[u].val);
if(!inque[vis])
{
inque[vis]=true;
q.push(vis);
}
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL),cout.tie(NULL);
cin>>n>>m;
for(int i=1;i<=n;i++) cin>>cost[i];
for(int i=1;i<=m;i++)
{
int x,y,z;
cin>>x>>y>>z;
if(z==1)
{
addedge_forward(x,y,cost[y]);
addedge_back(y,x,cost[x]);
}
if(z==2)
{
addedge_forward(x,y,cost[y]);
addedge_forward(y,x,cost[y]);
addedge_back(y,x,cost[x]);
addedge_back(x,y,cost[x]);
}
}
spfa_forward(1);
spfa_back(n);
int ans=-100000000;
for(int i=1;i<=n;i++) ans=max(ans,max_cost[i]-min_cost[i]);
cout<<ans<<endl;
return 0;
}
QQ40523591~欢迎一起学习交流~