codeforces 711C. Bear and Tree Jumps(树上距离)
来源:互联网 发布:jersey解析 json 编辑:程序博客网 时间:2024/05/14 21:44
题目链接
C. Bear and Tree Jumps
分析
其实题解已经说的很清楚了,我最开始不理解的一点在于如何计算剩余
题解搬运工
AC code
#include <bits/stdc++.h>using namespace std;typedef long long LL;const int maxn = 2e5+10;std::vector<int> G[maxn];int tatol_sub[maxn];int cnt_sub[maxn][5];//子树中每个剩余的点的总数LL ans;LL n,k;int sub_mod(int a,int b){ return ((a-b)%k+k)%k;}void dfs(int u,int p,int dep){ cnt_sub[u][dep%k] = tatol_sub[u] = 1; for(int v: G[u]){ if(v!=p){ dfs(v,u,dep+1); for(int i=0 ; i<k ; ++i){ for(int j =0 ; j<k ; ++j){ int remain = sub_mod(i+j,dep*2);//当前子树中两个节点的距离 int need = sub_mod(k,remain); ans+=(LL)need*cnt_sub[u][i]*cnt_sub[v][j]; } } for(int i = 0 ; i<k ; ++i) cnt_sub[u][i]+=cnt_sub[v][i]; tatol_sub[u]+=tatol_sub[v]; } } ans+=(n-tatol_sub[u])*tatol_sub[u];}int main(int argc, char const *argv[]) { cin>>n>>k; ans = 0; for(int i=0 ; i<n-1 ; ++i){ int u,v; cin>>u>>v; G[u].push_back(v); G[v].push_back(u); } dfs(1,-1,0); std::cout << ans/k << '\n'; return 0;}
0 0
- codeforces 711C. Bear and Tree Jumps(树上距离)
- CF771C:Bear and Tree Jumps(树形dp & 树上距离和)
- codeforces D. Bear and Tree Jumps
- codeforces 791D Bear and Tree Jumps
- Codeforces 711C. Bear and Tree Jumps【树形dp好题】
- Codeforces Round #405 Div. 1 B. Bear and Tree Jumps
- codeforces 405 D. Bear and Tree Jumps 树形dp
- Codeforces 791D Bear And Tree Jumps 树形DP
- Codeforces Round #405 D. Bear and Tree Jumps 树形DP
- CF791D-Bear and Tree Jumps
- 791D Bear and Tree Jumps
- CF Bear and Tree Jumps树形DP
- Codeforces790B Bear and Tree Jumps -- 树形DP
- Codeforces790B. Bear and Tree Jumps 【树型DP】
- Codeforces 658C Bear and Forgotten Tree 3【构造】
- CodeForces 658C Bear and Forgotten Tree 3(构造)
- Codeforces 658C Bear and Forgotten Tree 3【思维】
- Codeforces 842 C. Ilya And The Tree 树上dp
- 在Eclipse中使用JUnit4进行单元测试(高级篇)
- Java实现环形队列
- MySQL中光标的使用
- 算法:LeetCode207 Course Schedule
- PAT L2-006. 树的遍历
- codeforces 711C. Bear and Tree Jumps(树上距离)
- http状态码
- 关于初学python爬虫的一点问题总结(三)
- Z-26 Two names' abbreviations
- hadoop之hdfs和yarn
- Java中标准输入操作的几点总结
- 关于Activity之间传递数据的6种方式
- 1483 区间价值
- go语言-文件夹复制