Optimal trade (memory search)

Question link: [NOIP2009 Improvement Group] Optimal Trade-Luogu

Idea: The label of this question is SPFA, but I think this question can be searched using memory. Use two sets of dfs to store the minimum value on the road from 1 to point i into the min array, and store the minimum value from point i to point n. The maximum value is stored in the max group, and finally the maximum difference between the min and max arrays is traversed and output. Among them, the points connected to each point are traversed with the help of vector container.

AC code:

#include<bits/stdc++.h>
using namespace std;
vector<int>way_min[110000];
vector<int>way_max[110000];
int value[110000],minn[110000],maxx[110000];
void dfs_min(int x,int m)
{ 
	if(m>=minn[x])
	return ;
	m=min(m,value[x]);
	minn[x]=m;
	for(int i=0;i<way_min[x].size();i++)
	{
		dfs_min(way_min[x][i],m);
	}
}
void dfs_max(int x,int m)
{
	if(m<=maxx[x])
	return ;
	m=max(m,value[x]);
	maxx[x]=m;
	for(int i=0;i<way_max[x].size();i++)
	{
		dfs_max(way_max[x][i],m);
	}
}
int main()
{
	int n,m,x,y,z,ans=0;
	cin>>n>>m;
	for(int i=1;i<=n;i++)
	{
		cin>>value[i];
		minn[i]=1000;
		maxx[i]=-1000;
	}
	for(int i=1;i<=m;i++)
	{
		cin>>x>>y>>z;
		way_min[x].push_back(y);
		way_max[y].push_back(x);
		if(z==2)
		{
			way_min[y].push_back(x);
			way_max[x].push_back(y);
		}
	}
	dfs_min(1,value[1]);
	dfs_max(n,value[n]);
	for(int i=1;i<=n;i++)
	ans=max(ans,maxx[i]-minn[i]);
	cout<<ans<<endl;
	return 0;
}

Guess you like

Origin blog.csdn.net/weixin_74088105/article/details/131878572