codeforces 461B Appleman and Tree
来源:互联网 发布:php 日期格式 编辑:程序博客网 时间:2024/05/17 04:55
树形dp。感谢杰神指导。
之前看过好几个人的题解,但还是不大懂他们的做法。后来杰神跟我讲了一下他的做法,思路很清晰。
题意:
给你一颗树,节点被染成黑色或者白色。现在要你砍掉一些边,使得每个连通块有且仅有一个黑点。问你共有几种方案。
思路:
dp[i][0]:包含 i 在内的连通块中无黑点的方案数的种数。
dp[i][1]:包含 i 在内的连通块中有黑点的方案数的种数。
考虑一下转移(共有 4 种情况,一一列举即可):(v为 i 的子节点)
具体查看代码中的解释;
AC代码:
#include <cstring>#include <cstdlib>#include <cstdio>#include <iostream>#include <algorithm>#include <vector>typedef long long ll;using namespace std;const int MAXN = 1e5+5;const int MOD = 1000000007; vector <int> gra[MAXN];ll dp[MAXN][2];int mark[MAXN], n;inline int read(){ char ch = getchar(); int res = 0; while(ch >= '0' && ch <= '9') { res = res*10+(ch-'0'); ch = getchar(); } return res;}void dfs(int u){ if(mark[u] == 1) dp[u][1] = 1, dp[u][0] = 0; else dp[u][1] = 0, dp[u][0] = 1; for(int i = 0;i < gra[u].size(); i++) { int v = gra[u][i]; dfs(v); //dp[u][1]*(dp[v][1]+dp[v][0]) : 乘以dp[v][1]是u,v间的边可以断开; 乘以dp[v][0]是因为u,v间的边不断,两者都转移到dp[i][1] //dp[u][0]*dp[v][1] :乘以dp[v][1],v节点有黑点,u节点没黑点,就转移到dp[u][1]来了。 dp[u][1] = (dp[u][1]*(dp[v][1]+dp[v][0]) + dp[u][0]*dp[v][1])%MOD; //dp[u][0]*dp[v][0]:u,v边不断开; //dp[u][0]*dp[v][1]:u,v边断开。 dp[u][0] = (dp[u][0]*dp[v][0] + dp[u][0]*dp[v][1])%MOD; }}int main(){ n = read(); int tmp; for(int i = 0;i < n-1; i++) { tmp = read(); gra[tmp].push_back(i+1); } for(int i = 0;i < n; i++) { tmp = read(); mark[i] = tmp; } // dfs(0); cout<<dp[0][1]<<endl; return 0;}
0 0
- Codeforces 461 B. Appleman and Tree
- codeforces 461B Appleman and Tree
- codeforces 461B Appleman and Tree
- 【codeforces】 461B Appleman and Tree
- Codeforces 461B Appleman and Tree
- Codeforces 461B Appleman and Tree
- codeforces 461B B. Appleman and Tree(树形dp)
- Appleman and Tree - CodeForces 461 B 树形dp
- Codeforces 461B - Appleman and Tree 树状DP
- Codeforces 461B Appleman and Tree(树形dp)
- 【CodeForces】461B Appleman and Tree 树型DP
- codeforces 461B Appleman and Tree (树形dp)
- Codeforces Round #263 (Div.1) B. Appleman and Tree
- Codeforces Round #263 (Div. 1) B. Appleman and Tree
- Codeforces Round #263 (Div. 1 - B) Appleman and Tree
- Codeforces Round #263 (Div. 1) B. Appleman and Tree
- CF 461B - Appleman and Tree(树形DP)
- CF 461B Appleman and Tree (树形dp)
- pat 1002. A+B for Polynomials (25)
- hdu-3555-Bomb
- 矩阵转置
- ExpandableListView.setOnChildClickListener获取不到点击事件 (
- bzoj 1709: [Usaco2007 Oct]Super Paintball超级弹珠
- codeforces 461B Appleman and Tree
- Jsp/Servlet基础-动态INCLUDE与静态INCLUDE的区别
- OpenCV最小外接矩形
- 概率图模型(PGM)学习笔记(五)——模板模型
- java.lang.IllegalStateException: get field slot from row 0 col -1 failed 异常错误
- yuv422打包模式转平面模式
- 分配问题 二分最佳匹配问题
- usb cdc
- 不重新启动挂载一个阿里或者腾讯云磁盘