P2656 采蘑菇 题解
AmamiyaYuuko · · 题解
由于题目中没有类似“体力”的限制,不难想到最优的方法是在一个环上一直走直到没有新蘑菇长出,然后再走向下一个环继续这个步骤。
原图是有向图,可以用 Tarjan 算法求出强连通分量。对于每个强连通分量,预处理出在这个连通分量中一直走能获得的所有的蘑菇数量。
接下来将
在这里有一些细节问题:
-
恢复系数是浮点数,运算时会出现精度误差。由于限定了恢复系数
p 为一位小数,可以用一个int存下10p 。设当前蘑菇数位w ,则新长出的蘑菇数为\lfloor \dfrac{w \times 10p}{10} \rfloor 。 -
注意 DP 数组的边界情况,对于不包含
S 的连通分量,初始值应设为- \infty 。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <queue>
template <class T>
inline void read(T &x) {
x = 0;
int f = 0;
char ch = getchar();
while (!isdigit(ch)) { f |= ch == '-'; ch = getchar(); }
while (isdigit(ch)) { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); }
x = f ? -x : x;
return ;
}
typedef unsigned long long uLL;
typedef long long LL;
struct Edge {
int to, w, p;
} ;
std::queue<int> q;
std::vector<Edge> g[80010], G[80010];
int scc[80010], sta[80010], dfn[80010], low[80010], w[80010], f[80010], in[80010];
int n, m, top, cnt, s, sc, ans;
bool ins[80010];
void tarjan(int x) {
dfn[x] = low[x] = ++cnt;
sta[++top] = x;
ins[x] = true;
for (auto i : g[x]) {
if (ins[i.to]) {
low[x] = std::min(low[x], dfn[i.to]);
} else if (!dfn[i.to]) {
tarjan(i.to);
low[x] = std::min(low[x], low[i.to]);
}
}
if (dfn[x] == low[x]) {
++sc;
while (sta[top] != x) {
scc[sta[top]] = sc;
ins[sta[top]] = false;
--top;
}
scc[sta[top]] = sc;
ins[sta[top]] = false;
--top;
}
}
int main() {
read(n), read(m);
for (int i = 1, u, v, w; i <= m; ++i) {
double p;
scanf("%d%d%d%lf", &u, &v, &w, &p);
g[u].push_back((Edge){v, w, (int)(p * 10)});
}
read(s);
for (int i = 1; i <= n; ++i) {
if (!dfn[i]) {
tarjan(i);
}
}
for (int i = 1; i <= n; ++i) {
for (auto j : g[i]) {
if (scc[i] != scc[j.to]) {
G[scc[i]].push_back((Edge){scc[j.to], j.w, 0});
++in[scc[j.to]];
} else {
int tw = j.w, val = 0;
while (tw) {
val += tw;
tw = tw * j.p / 10;
}
w[scc[i]] += val;
}
}
}
for (int i = 1; i <= sc; ++i) {
f[i] = -2e9;
if (!in[i]) {
q.push(i);
}
}
f[scc[s]] = w[scc[s]];
while (!q.empty()) {
int u = q.front();
q.pop();
for (auto i : G[u]) {
f[i.to] = std::max(f[i.to], f[u] + i.w + w[i.to]);
--in[i.to];
if (!in[i.to]) q.push(i.to);
}
}
for (int i = 1; i <= sc; ++i) ans = std::max(ans, f[i]);
printf("%d\n", ans);
return 0;
}