版本比较
123
正文
增加 35 行删除 125 行
1234567812345101112131415161718192021222367252627282930313233343536373839404142434445464748495051528954555657585960616210111213141516171819646566676869707172737475767778202180818283848586878889909192939495969798991002223242526272829303110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013132333435363738394041```cpp// P1073 [NOIP 2009 提高组] 最优贸易#include <iostream>#include <algorithm>#include <vector>#include <stack>#include <queue>#include <cstring>$$(1) |x - 5| + |2x - 13| (x > 5) $$由于 $ x > 5 $,那么 $ |x - 5| = x - 5$。
const int MAXN = 1e5 + 5;// GLOBALint n, m, ans;int val[MAXN];std::vector<int> e[MAXN], e2[MAXN], e3[MAXN];// TARJANint sc, timer;int dfn[MAXN], low[MAXN];int scc[MAXN], max[MAXN], min[MAXN];bool inS[MAXN];std::stack<int> stk;// TOPOSORTint inD[MAXN], dp[MAXN];bool vis[MAXN];由于 $2x = 10$, 所以 $2x - 13$ 不确定它的符号,故分类讨论:
void Tarjan(int u){ dfn[u] = low[u] = ++timer; stk.push(u), inS[u] = 1; for (int v : e[u]) { if (!dfn[v]) { Tarjan(v); low[u] = std::min(low[u], low[v]); } else if (inS[v]) low[u] = std::min(low[u], dfn[v]); } if (dfn[u] == low[u]) { int v; sc++; do { v = stk.top(); stk.pop(), inS[v] = 0; scc[v] = sc; max[sc] = std::max(max[sc], val[v]); min[sc] = std::min(min[sc], val[v]); } while (v != u); }}$(1)$ $x \ge \frac{13}{2}$ 时,$ |2x - 13| = 2x - 13$,
void RebuildGraph(){ for (int u = 1; u <= n; u++) for (int v : e[u]) if (scc[u] != scc[v] && scc[u] && scc[v]) // 注意原图没跑完 { e2[scc[u]].push_back(scc[v]); // 建边建的是SCC! e3[scc[v]].push_back(scc[u]); }此时 $$ \begin{equation*}\begin{split}原式 &= x - 5 + 2x - 13\\ &= 3x - 18 \end{split} \end{equation*} $$
for (int i = 1; i <= n; i++) { std::sort(e2[i].begin(), e2[i].end()); e2[i].erase(std::unique(e2[i].begin(), e2[i].end()), e2[i].end()); for (int v : e2[i]) inD[v]++; // 去重后再统计! }}void DFS(int x) // 从n能到达的点{ vis[x] = 1; for (int i : e3[x]) // 反图 if (!vis[i]) DFS(i);}$(2)$ $x \le \frac{13}{2}$ 时,$ |2x - 13| = 13 - 2x$,
void Toposort(){ std::queue<int> q; q.push(scc[1]); // 注意从一号节点开始 DFS(scc[n]); // 原图不一定联通,前面用Tarjan从1到i,现在从n到i dp[scc[1]] = min[scc[1]]; while (!q.empty()) { int u = q.front(); q.pop(); for (int v : e2[u]) { dp[v] = std::min(dp[v], std::min(min[v], dp[u])); if (--inD[v] == 0) q.push(v); } } for (int i = 1; i <= sc; i++) if (vis[i]) ans = std::max(ans, max[i] - dp[i]);}此时$$ \begin{equation*}\begin{split}原式 &= x - 5 + 13 - 2x\\ &= -x + 8 \end{split} \end{equation*} $$
int main(){ // READ std::cin >> n >> m; for (int i = 1; i <= n; i++) std::cin >> val[i]; for (int i = 1; i <= m; i++) { int u, v, op; std::cin >> u >> v >> op; if (op == 1) e[u].push_back(v); else { e[u].push_back(v); e[v].push_back(u); } } // MAIN memset(min, 0x3f, sizeof(min)); memset(max, -1, sizeof(max)); memset(dp, 0x3f, sizeof(dp)); Tarjan(1); // 只考虑到达1的点 RebuildGraph(); Toposort(); // OUTPUT std::cout << ans; return 0;}``` 这即是两种情况,综上:$$原式=\begin{cases}
3x - 18 & (x \ge \frac{13}{2}) \\ -x + 8 & (x \le \frac{13}{2}) \end{cases}$$