[HAOI2010]软件安装
题面:Luogu
题解:缩点+树形dp
题目还是很简单的,缩一下点,在新图上跑dp
这个dp连我都能一眼,可知难度多低
注意缩完点,建完新图后,再新建一个根,连到每一个入度为0的点上,再dfs
#include<bits/stdc++.h>
using namespace std;
inline void read(int& x)
{
x = 0; char c = getchar();
while (!isdigit(c)) c = getchar();
while (isdigit(c)) x = x * 10 + c - '0', c = getchar();
}
#define maxn 2005
int n, m;
struct Graph
{
struct Edge
{
int fr, to;
}eg[maxn << 1];
int head[maxn], edgenum;
inline void add(int fr, int to)
{
eg[++edgenum] = { head[fr],to };
head[fr] = edgenum;
}
int dfn[maxn], low[maxn], dfn_clock, col[maxn], colnum, vis[maxn];
stack<int> sta;
#define to eg[i].to
void paint(int rt)
{
vis[rt] = 0; sta.pop();
col[rt] = colnum;
}
void Tarjan(int rt)
{
low[rt] = dfn[rt] = ++dfn_clock;
vis[rt] = 1; sta.push(rt);
for (int i = head[rt]; i; i = eg[i].fr)
{
if (!dfn[to]) Tarjan(to), low[rt] = min(low[rt], low[to]);
else if (vis[to]) low[rt] = min(low[rt], dfn[to]);
}
if (low[rt] == dfn[rt])
{
++colnum;
while (sta.top() != rt) paint(sta.top());
paint(rt);
}
}
}G, g;
int w[maxn], v[maxn], d[maxn];
int siz[maxn], sum[maxn], deg[maxn], dp[maxn][maxn];
void dfs(int rt)
{
for (int i = siz[rt]; i <= m; ++i) dp[rt][i] = sum[rt];
for (int i = g.head[rt]; i; i = g.eg[i].fr)
{
dfs(g.to);
for (int j = m; j >= siz[rt]; --j)
for (int k = 0; k <= j - siz[rt]; ++k)
dp[rt][j] = max(dp[rt][j], dp[rt][j - k] + dp[g.to][k]);
}
}
int main()
{
read(n), read(m);
for (int i = 1; i <= n; ++i) read(w[i]);
for (int i = 1; i <= n; ++i) read(v[i]);
for (int i = 1; i <= n; ++i)
{
read(d[i]);
if (!d[i]) continue;
G.add(d[i], i);
}
for (int i = 1; i <= n; ++i)
if (!G.dfn[i]) G.Tarjan(i);
for (int i = 1; i <= n; ++i)
{
siz[G.col[i]] += w[i], sum[G.col[i]] += v[i];
if (G.col[d[i]] == G.col[i] || !d[i]) continue;
g.add(G.col[d[i]], G.col[i]); ++deg[G.col[i]];
}
for (int i = 1; i <= G.colnum; ++i)
if (!deg[i]) g.add(G.colnum + 1, i);
dfs(G.colnum + 1);
printf("%d\n", dp[G.colnum + 1][m]);
return 0;
}
一切伟大的行动和思想,都有一个微不足道的开始。
There is a negligible beginning in all great action and thought.
There is a negligible beginning in all great action and thought.