简要题意:
给定一个图,每个点有点权。一个人从 1 1 1 号点出发,可以任意走路径,也可以任意停止旅行。每个点的点权表示水晶球的价格,初始这个人没有水晶球,可以在任意点卖出,也可以在任意点买。只能买卖一次。当然也可以不卖。求他的最大盈利。(赚不了则输出 0 0 0)
本题是 NOIP 2009 \text{NOIP 2009} NOIP 2009 提高组 第三题.
算法一
对于 10 % 10 \% 10% 的数据, 1 ≤ n ≤ 6 1 \leq n \leq 6 1≤n≤6.
爆搜即可,随你什么姿势都可以过。
时间复杂度: O ( wys ) O(\text{wys}) O(wys).
实际得分: 10 p t s 10pts 10pts.
算法二
对于 30 % 30 \% 30% 的数据, 1 ≤ n ≤ 100 1 \leq n \leq 100 1≤n≤100.
显然,我们可以对每个节点 x x x 遍历一遍,考虑从 x x x 买进,何处的卖出价格最高。考虑统计一遍即可。
时间复杂度: O ( n 2 ) O(n^2) O(n2).
实际得分: 30 p t s 30pts 30pts.
算法三
对于 50 % 50 \% 50% 的数据,不存在环。
不存在环?这很简单啊。
对于 每条路径,统计出该条路径的最小值与最大值,作差即可。
你可以选择记录路径。可是不需要,你可以在搜索的时候记录。
时间复杂度: O ( n ) O(n) O(n).
实际得分: 50 p t s 50pts 50pts.
算法四
对于 100 % 100 \% 100% 的数据, 1 ≤ n ≤ 1 0 5 1 \leq n \leq 10^5 1≤n≤105.
显然,算法三已经非常接近正解。
从 1 1 1 遍历,对当前节点 x x x,记录之前路径的最小值并考虑在当前卖出的答案,然后更新最小值即可!
时间复杂度: O ( n ) O(n) O(n).
实际得分: 100 p t s 100pts 100pts.
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+1;
inline int read() {int f=1; char ch=getchar(); while(!isdigit(ch)) {if(ch=='-') f=-f; ch=getchar();}
int x=0; while(isdigit(ch)) x=(x<<3)+(x<<1)+ch-'0',ch=getchar(); return x*f;}
vector<int> G[N];
int n,m,f[N],g[N],a[N];
inline void dfs(int x,int val,int pre) {
bool fl=1; val=min(a[x],val);
if(g[x]>val) g[x]=val,fl=0;
int coin=max(f[pre],a[x]-val);
if(f[x]<coin) f[x]=coin,fl=0;
if(fl) return;
for(int i=0;i<G[x].size();i++) dfs(G[x][i],val,x);
}
int main() {
n=read(),m=read();
memset(g,0x3f,sizeof(g));
for(int i=1;i<=n;i++) a[i]=read();
while(m--) {
int x=read(),y=read(),z=read();
G[x].push_back(y);
if(z==2) G[y].push_back(x);
} dfs(1,1e9,0);
printf("%d\n",f[n]);
return 0;
}