diff --git a/TangDou/Topic/HuanGenDp/P3047.cpp b/TangDou/Topic/HuanGenDp/P3047.cpp new file mode 100644 index 0000000..ca2d7ef --- /dev/null +++ b/TangDou/Topic/HuanGenDp/P3047.cpp @@ -0,0 +1,75 @@ +#include +#define re register +typedef long long ll; +using namespace std; +inline ll read() { + ll a = 0, f = 1; + char c = getchar(); + while (c < '0' || c > '9') { + if (c == '-') f = -1; + c = getchar(); + } + while (c >= '0' && c <= '9') { + a = a * 10 + c - '0'; + c = getchar(); + } + return a * f; +} // 好用的快读 +ll n, q; +ll head[200010], dp[200010][21]; +struct ljj { + ll to, stb; +} a[200010]; +ll s = 0; +inline void insert(ll x, ll y) { + s++; + a[s].stb = head[x]; + a[s].to = y; + head[x] = s; +} +inline void dfs(ll x, ll fa) { + for (re ll i = head[x]; i; i = a[i].stb) { + ll xx = a[i].to; + if (xx == fa) + continue; + dfs(xx, x); + for (re ll j = 1; j <= q; j++) + dp[x][j] += dp[xx][j - 1]; // 第一遍dp + } +} +inline void dfs1(ll x, ll fa) { + for (re ll i = head[x]; i; i = a[i].stb) { + ll xx = a[i].to; + if (xx == fa) + continue; + // 在第一次遍历时 dp[1][2] 包括了 dp[2][1] 2的子树权值; + // 然鹅 ans在统计dp[2][3] 的时候也加上了 dp[2][1] 2的子树权值; + // 第二次遍历 dp[2][3] 又加上了 dp[2][1]; + // 所以需要简单容斥一下; + for (re ll j = q; j >= 2; j--) + dp[xx][j] -= dp[xx][j - 2]; // 简单容斥 + for (re ll j = 1; j <= q; j++) + dp[xx][j] += dp[x][j - 1]; // 第二遍dp + dfs1(xx, x); + } +} +int main() { + n = read(); + q = read(); + for (re ll i = 1; i < n; i++) { + ll x = read(), y = read(); + insert(x, y); + insert(y, x); + } + for (re ll i = 1; i <= n; i++) + dp[i][0] = read(); // 每个节点往外0距离,就是它本身的权值; + dfs(1, 0); + dfs1(1, 0); + for (re ll i = 1; i <= n; i++) { + ll ans = 0; + for (re ll j = 0; j <= q; j++) + ans += dp[i][j]; // ans统计答案 + printf("%lld\n", ans); + } + return 0; +} \ No newline at end of file diff --git a/TangDou/Topic/【换根】dfs专题.md b/TangDou/Topic/【换根】dfs专题.md index d20aa7a..a7882d8 100644 --- a/TangDou/Topic/【换根】dfs专题.md +++ b/TangDou/Topic/【换根】dfs专题.md @@ -681,7 +681,35 @@ int main() { return 0; } ``` -[USACO12FEB]Nearby Cows G + +#### [$P3047$ $Nearby$ $Cows$ $G$](https://www.luogu.com.cn/problem/P3047) + +https://www.cnblogs.com/wzx-RS-STHN/p/13414401.html + +**题目大意** +题目大意是给你一颗树,对于每一个节点$i$,求出范围$k$之内的点权之和。 + +看数据范围就知道暴力肯定是会$TLE$飞的,所以我们要考虑如何$dp$(代码习惯写$dfs$) + +仔细思考一下我们发现点$i$走$k$步能到达的点分为以下两种 + +- 在$i$的子树中(由$i$点往下) +- 经过$i$的父亲(由$i$点往上) + +这样的问题一般可以用两次$dfs$解决 + +定义状态: +- $f[i][j]$表示$i$点往下$j$步范围内的点权之和 +- $g[i][j]$表示$i$点往上和往下走$j$步范围内点权之和 + +第一次$dfs$我们求出所有的$f[n][k]$,这个比较简单,对于节点$u$和其儿子$v$,$f[u][k] += f[v][j - 1]$就行了。(第一次$dfs$已知叶子节点推父亲节点) + +第二次$dfs$我们通过已经求出的$f$数组推$g$数组,对于$u$和$u$的儿子$v$, +$$g[v][k] += (g[u][k - 1] - f[v][k - 2])$$ + +注意数组下表不要越界。$g[i][j]$的初始值应该赋为$f[i][j]$,因为根节点的$g[i][j]$就是$f[i][j]$。(第二次$dfs$已知父亲节点推儿子节点) + + [COCI2014-2015#1]Kamp