https://www.luogu.org/problem/P2515
读完题相信已经思路明确了
有依赖关系的连边,
但可能这整个图不连通,并且还有可能出现环
如果出现环的话,要选其中一个就必须吧整个环都选上(应该很好理解吧)
那么显然这要求我们进行tarjan缩点
缩点后是一个有向无环的森林,考虑建一个超级源点
对于每个入度为零的,与他相连
之后就是一个树上背包了(注意循环的顺倒序)
code:
#include
#include
#include
#include
#include
using namespace std;
inline int read() {
int res = 0; bool bo = 0; char c;
while (((c = getchar()) < '0' || c > '9') && c != '-');
if (c == '-') bo = 1; else res = c - 48;
while ((c = getchar()) >= '0' && c <= '9')
res = (res << 3) + (res << 1) + (c - 48);
return bo ? ~res + 1 : res;
}
const int N = 105, M = 505;
int n, m, W[N], V[N], f[N][M], ecnt, nxt[M], adj[N], go[M], top,
sta[N], dfn[N], low[N], times, num, bel[N], cost[N], val[N], ecnt2,
nxt2[M], adj2[N], go2[M], d[N];
bool ins[N], G[N][N];
void add_edge(int u, int v) {
nxt[++ecnt] = adj[u]; adj[u] = ecnt; go[ecnt] = v;
}
void add_edge2(int u, int v) {
nxt2[++ecnt2] = adj2[u]; adj2[u] = ecnt2; go2[ecnt2] = v;
}
void Tarjan(int u) {
dfn[u] = low[u] = ++times;
sta[++top] = u; ins[u] = 1;
for (int e = adj[u], v; e; e = nxt[e])
if (!dfn[v = go[e]]) {
Tarjan(v);
low[u] = min(low[u], low[v]);
}
else if (ins[v]) low[u] = min(low[u], dfn[v]);
if (dfn[u] == low[u]) {
int v; bel[u] = ++num; ins[u] = 0;
while (v = sta[top--], v != u) bel[v] = num, ins[v] = 0;
}
}
void dp(int u) {
int i, j;
for (i = cost[u]; i <= m; i++) f[u][i] = val[u];
for (int e = adj2[u], v; e; e = nxt2[e]) {
dp(v = go2[e]);
for (i = m - cost[u]; i >= 0; i--)
for (j = 0; j <= i; j++)
f[u][i + cost[u]] = max(f[u][i + cost[u]],f[u][i + cost[u] - j] + f[v][j]);
//我想你会和我一样对这个转移式子很不解吧,为什么和平时写的不一样呢?
//这个方程只有选当前这个点的情况,为什么?因为他们有依恋关系呀,只有选了当前的这个点才可以继续向下dp
//再就是这个dp的是点权
}
}
int main() {
int i, j, x; n = read(); m = read();
for (i = 1; i <= n; i++) W[i] = read();
for (i = 1; i <= n; i++) V[i] = read();
for (i = 1; i <= n; i++) if (x = read()) add_edge(x, i);
for (i = 1; i <= n; i++) if (!dfn[i]) Tarjan(i);
for (i = 1; i <= n; i++) {
cost[bel[i]] += W[i]; val[bel[i]] += V[i];
for (int e = adj[i]; e; e = nxt[e])
if (bel[i] != bel[go[e]]) G[bel[i]][bel[go[e]]] = 1,
d[bel[go[e]]]++;
}
for (i = 1; i <= num; i++) for (j = 1; j <= num; j++)
if (G[i][j]) add_edge2(i, j);
for (i = 1; i <= num; i++) if (!d[i])
add_edge2(num + 1, i);
printf("%d\n", (dp(num + 1), f[num + 1][m]));
return 0;
}