您的位置:首页 > 其它

Codevs 1378 选课

2015-05-10 19:18 302 查看
题意:

(中文)

思路:

由于父子关系特别清晰,由于每个点都只有一个前驱,并且只有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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: