给你一棵 \(n\) 个点的树,点带权,对于每个节点求出距离它不超过 \(k\) 的所有节点权值和 \(m_i\) 随便定一个根,设\(f[i][j]\)表示只考虑子树,距离为\(j\)的权值和,\(g[i][j]\)表示考虑子树和父树,距离为\(j\)的权值和,显然答案可以用\(g\)表示 \(f[p][0]=w[p]\) \(f[p][k]=\sum f[q][k-1]\) \(g[1][k]=f[1][k]\) \(g[p][0]=w[p]\) 对\(g\)的计算,考虑容斥 \[g[q][…
$k$ 十分小,直接暴力维护 $1$~$k$ 的答案即可. 然后需要用父亲转移到儿子的方式转移一下. Code: #include <bits/stdc++.h> #define M 23 #define N 100005 #define setIO(s) freopen(s".in","r",stdin) using namespace std; int n,K,edges; int f[N][M],hd[N],to[N<<1],nex[N…
传送门 dp[i][j][0] 表示点 i 在以 i 为根的子树中范围为 j 的解 dp[i][j][1] 表示点 i 在除去 以 i 为根的子树中范围为 j 的解 状态转移就很好写了 ——代码 #include <cstdio> #include <cstring> #include <iostream> #define N 100001 int n, k, cnt; int f[N], dp[N][21][2], head[N], to[N << 1],…
P3047 [USACO12FEB]附近的牛Nearby Cows 农民约翰已经注意到他的奶牛经常在附近的田野之间移动.考虑到这一点,他想在每一块土地上种上足够的草,不仅是为了最初在这片土地上的奶牛,而且是为了从附近的田地里去吃草的奶牛. 具体来说,FJ的农场由N块田野构成(1 <= n <= 100,000),每两块田野之间有一条无向边连接(总共n-1条边).FJ设计了农场,任何两个田野i和j之间,有且只有一条路径连接i和j.第 i块田野是C(i)头牛的住所,尽管奶牛们有时会通过k条路到达其…
P3047 [USACO12FEB]附近的牛Nearby Cows 题目描述 Farmer John has noticed that his cows often move between nearby fields. Taking this into account, he wants to plant enough grass in each of his fields not only for the cows situated initially in that field, but…
P3047 [USACO12FEB]附近的牛Nearby Cows 题目描述 Farmer John has noticed that his cows often move between nearby fields. Taking this into account, he wants to plant enough grass in each of his fields not only for the cows situated initially in that field, but…
题目描述 Farmer John has noticed that his cows often move between nearby fields. Taking this into account, he wants to plant enough grass in each of his fields not only for the cows situated initially in that field, but also for cows visiting from nearby…
题目描述 Farmer John has noticed that his cows often move between nearby fields. Taking this into account, he wants to plant enough grass in each of his fields not only for the cows situated initially in that field, but also for cows visiting from nearby…
传送门 解题思路 树形dp,看到数据范围应该能想到是O(nk)级别的算法,进而就可以设出dp状态,dp[x][j]表示以x为根的子树,距离它为i的点的总和,第一遍dp首先自底向上,dp出每个节点的子树中到他距离为j的,转移方程dp[x][j]=dp[u][j-1] ,第二遍dp自顶向下,dp出每个节点父亲那头的距离为j的,转移方程dp[u][j]+=dp[x][j-1]-dp[u][j-2] 代码 //dp[x][j] 以i为根的子树,距离为j的牛的和 //dp[x][j]+=dp[u][j-1…
首先可以把题目转化一下:把树拆成若干条链,每条链的颜色为其所在的树的颜色,然后排放所有的链成环,求使得相邻位置颜色不同的排列方案数. 然后本题分为两个部分:将一棵树分为1~n条不相交的链的方案数:将这些链安排顺序使得不存在两条相邻的链来自同一棵树. 第一部分显然可以O(n2)树形DP,f[i][j][0/1/2]表示i及其子树j条链,i向儿子连出0/1/2条边的方案数,然后直接背包DP即可.看似O(n3)的树形背包DP其实是O(n2)的.证明复杂度:其实DP时只循环到sz[u]/sz[v]即可,…