洛谷P1073

Gong Jin Lv6

手打代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#include<bits/stdc++.h>
using namespace std;
const int N=100005;
int scc[N],siz[N],cnt;
int stk[N],instk[N],top;
int dfn[N],low[N],tot;
int n,m,ans;
int w[N],nw[N],dp[N];
int sccmax[N],sccmin[N],can[N];
vector<int>G[N],ne[N],oe[N];
void tarjin(int x){
dfn[x]=low[x]=++tot;
stk[++top]=x;
instk[x]=1;
for(auto y : G[x]){
if(!dfn[y]){
tarjin(y);
low[x]=min(low[x],low[y]);
}
else if(instk[y]){
low[x]=min(low[x],dfn[y]);
}
}
if(dfn[x]==low[x]){
++cnt;
int y;
sccmin[cnt]=INT_MAX;
do{
sccmax[cnt]=max(sccmax[cnt],w[y]);
sccmin[cnt]=min(sccmin[cnt],w[y]);
y=stk[top--];
instk[y]=0;
scc[y]=cnt;
++siz[cnt];
}while(y!=x);
}
}

void dfs(int x){
can[x]=1;
for(auto y : oe[x])if(!can[y])dfs(y);
}

int main(){
int u,v,p;
cin>>n>>m;
for(int i=1;i<=n;i++){
cin>>w[i];
}
for(int i=1;i<=m;i++){
cin>>u>>v>>p;
G[u].push_back(v);
if(p==2)G[v].push_back(u);
}
tarjin(1);//Starting from 1.
for(int i=1;i<=n;i++){
nw[scc[i]]+=w[i];
for(int j : G[i]){
if(scc[i]!=scc[j]&&scc[i]&&scc[j]){
ne[scc[i]].push_back(scc[j]);
oe[scc[j]].push_back(scc[i]);
}
}
}
dfs(scc[n]);
memset(dp,0x3f,sizeof dp);
dp[scc[1]]=sccmin[scc[1]];
for(int i=cnt;i;i--){
for(int j : ne[i]) dp[j]=min(dp[j],min(dp[i],sccmin[i]));
}
for(int i=1;i<=cnt;i++){
if(can[i]){
ans=max(ans,sccmax[i]-dp[i]);
}
}
cout<<ans;
return 0;
}

AI分析

最优贸易问题:在一张有向图上从起点走到终点,途中先买入一次再卖出,求最大收益。代码先用 Tarjan 缩点,并在缩点时记录每个分量内的最高价和最低价;然后再枚举原图的边,若两端属于不同分量就建立新图。接着用一次 DFS 标记从终点能反向到达的分量,保证只在有效路径上计算。最后按缩点编号顺序做动态规划,维护到达每个分量时的最小买入价,并用该分量的最高价减去买入价更新答案。这样把环内交易和跨分量交易都完整考虑了。

另外,本题也可以用分层图最短路来理解:把状态分为未买入、已买入、已卖出三层。两种建模方式对比着学,能有效拓宽思路。

  • 标题: 洛谷P1073
  • 作者: Gong Jin
  • 创建于 : 2025-07-17 11:22:45
  • 更新于 : 2026-11-22 10:13:46
  • 链接: https://blog.zymc.net/2025/07/17/洛谷/洛谷P1073/
  • 版权声明: 版权所有 © Gong Jin,禁止转载。
评论
目录
洛谷P1073