Codevs 1378 选课
2015-05-10 19:18
302 查看
题意:
(中文)
思路:
由于父子关系特别清晰,由于每个点都只有一个前驱,并且只有n个关系,那么可以判断他们的关系是一个森林。对于每个根,如果不选择根点,此根以后的所有的点都不选择;如果选择根点,那么剩下的m - 1 - (此根代表的树选择的课程数)就分给剩下的森林来选择。
那么我们把森林转换成二叉树会更方便编程,所以我们在存储的时候就把关系变成一个二叉树来表示,左儿子表示根节点的孩子,右儿子表示根节点的兄弟。
Code:
(中文)
思路:
由于父子关系特别清晰,由于每个点都只有一个前驱,并且只有n个关系,那么可以判断他们的关系是一个森林。对于每个根,如果不选择根点,此根以后的所有的点都不选择;如果选择根点,那么剩下的m - 1 - (此根代表的树选择的课程数)就分给剩下的森林来选择。
那么我们把森林转换成二叉树会更方便编程,所以我们在存储的时候就把关系变成一个二叉树来表示,左儿子表示根节点的孩子,右儿子表示根节点的兄弟。
Code:
#include<cstdio> #include<cstdlib> #include<cstring> #include<cctype> #include<cmath> #include<algorithm> #include<iostream> #include<string> #include<vector> #include<bitset> #include<queue> #include<stack> #include<list> #include<map> #include<set> #define TEST #define LL long long #define Mt(f, x) memset(f, x, sizeof(f)); #define rep(i, s, e) for(int i = (s); i <= (e); ++i) #ifdef TEST #define See(a) cout << #a << " = " << a << endl; #define See2(a, b) cout << #a << " = " << a << ' ' << #b << " = " << b << endl; #define debug(a, s, e) rep(_i, s, e) {cout << a[_i] << ' ';} cout << endl; #define debug2(a, s, e, ss, ee) rep(i_, s, e) {debug(a[i_], ss, ee)} #else #define See(a) #define See2(a, b) #define debug(a, s, e) #define debug2(a, s, e, ss, ee) #endif // TEST const int MAX = 2e9; const int MIN = -2e9; const double eps = 1e-8; const double PI = acos(-1.0); using namespace std; const int N = 305; int s , tree [2], f ;//tree[i][0]代表i节点的儿子 //tree[i][1]代表i节点的兄弟 //f[i][k]代表i节点选择k个课能得到的最大学分 int max3(int a, int b, int c) { return max(a, max(b, c)); } int dfs(int node, int m) { if(node == 0 || m == 0) return 0; if(f[node][m] != -1) return f[node][m]; for(int i = 0; i < m; ++i) { f[node][m] = max3(f[node][m], dfs(tree[node][0], m - i - 1) + dfs(tree[node][1], i) + s[node],//选择根节点:此根节点的数选择m - i个课,剩下的i个分给后面的树来选择。 dfs(tree[node][1], m));//不选择根节点 } return f[node][m]; } int main() { int n, m; while(~scanf("%d%d", &n, &m)) { Mt(tree, 0); Mt(f, -1); for(int i = 1; i <= n; ++i)//森林转二叉树 { int bef; scanf("%d%d", &bef, &s[i]); if(bef == 0) bef = n + 1; tree[i][1] = tree[bef][0]; tree[bef][0] = i; } printf("%d\n", dfs(tree[n + 1][0], m));//tree[n + 1][0]存的是二叉树的根。 } return 0; }
相关文章推荐
- codevs 1378 选课
- codevs 1378选课 树形DP
- code vs 1378 选课(树形DP)
- 选课(codevs 1378)
- Codevs 1378 选课 树形DP
- 树形DP+(分组背包||二叉树,一般树,森林之间的转换)codevs 1378 选课
- codevs1278选课
- Codevs_P2972 选课
- Codevs_P1378 选课(树形DP+分组背包)
- 爱在心中(codevs 2822)
- 同余方程 (codevs1200)
- 二分+找规律 之 codevs 1083 Cantor表
- CODEVS 2800 送外卖
- Codevs1250 Fibonacci数列
- VSCODE常用插件记录—不定期更新
- win7下使用vscode搭建unity开发环境
- 【vijos P1914】【codevs 3904】[NOIP2014 普及组T4]子矩阵(dfs+状压dp)
- VS==UML==General Code Template
- [乱说]Electron Debug with VS Codee
- 【BZOJ2539】【codevs1221】丘比特的烦恼,trie树+几何判断+费用流