【P1304】【P1305】选课与选课输出方案

时间:2023-03-09 19:37:09
【P1304】【P1305】选课与选课输出方案

多叉树归

原题:

学校实行学分制。每门的必修课都有固定的学分,同时还必须获得相应的选修课程学分。学校开设了N(N<500)门的选修课程,每个学生可选课程的数量M是给定的。学生选修了这M门课并考核通过就能获得相应的学分。

  在选修课程中,有些课程可以直接选修,有些课程需要一定的基础知识,必须在选了其它的一些课程的基础上才能选修。例如《Frontpage》必须在选修了《Windows操作基础》之后才能选修。我们称《Windows操作基础》是《Frontpage》的先修课。每门课的直接先修课最多只有一门。两门课也可能存在相同的先修课。每门课都有一个课号,依次为1,2,3,…。

你的任务是为自己确定一个选课方案,使得你能得到的学分最多,并且必须满足先修课优先的原则。假定课程之间不存在时间上的冲突。

(1≤N≤500)

思路根上一个差不多,不过这里可以把多叉转成2叉,用左儿子右兄弟

所以这里f[x][y]的意义有点不一样,表示涉及到x,x的兄弟,x的儿子的方案的最优值

这样搞的话搞法就是先搞一下兄弟,表示不选x,然后把f[x][y]的初值设成f[brother[x]][y],然后再搞兄弟和儿子一起搞的最优值

枚举i,先搞f[brother][i],再搞f[child[x]][y-i-1],然后更新答案

需要设置一个超级根,f[x][y]表示的是上面说的意义↑的话,需要从child[root]开始搞

也可以直接搞多叉的,比较直观,不过似乎不好写

怎么搞方案呐

似乎DP都是这么搞方案的:如果当前阶段的值等于最优值在这个阶段的值(求最优值的时候存下来了),这个阶段就在方案中

具体到这道题上,首先如果f[x][y]==f[brother[x]][y],说明x没用,直接搞brother[x],为什么看上面的求法↑

然后枚举i,如果f[x][y]==f[brother[x]][i]+f[child[x]][y-i-1]+value[x],就进去搞brother[x],i和child[x],y-i-1

直接贴输出方案的代码:

 #include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int read(){int z=,mark=; char ch=getchar();
while(ch<''||ch>''){if(ch=='-')mark=-; ch=getchar();}
while(ch>=''&&ch<=''){z=(z<<)+(z<<)+ch-''; ch=getchar();}
return z*mark;
}
struct dcd{int child,brother,value;}tree[];
inline void insert_tree(int x,int y){
if(!tree[x].child) tree[x].child=y;
else{ tree[y].brother=tree[x].child; tree[x].child=y;}
}
int n,m;
int f[][];
bool have[];
void DP_tree(int x,int y){
if(f[x][y]) return ;
if(x==) return ; if(y==){ f[x][y]=; return ;}
DP_tree(tree[x].brother,y);//不选x,去搞brother
f[x][y]=max(f[x][y],f[tree[x].brother][y]);//别忘了还可以不选x选brother,这个要先处理一下
for(int i=;i<y;i++){
DP_tree(tree[x].brother,i);//搞brother,选i个
DP_tree(tree[x].child,y-i-);//搞child
f[x][y]=max(f[x][y],f[tree[x].brother][i]+f[tree[x].child][y-i-]+tree[x].value);
}
return ;
}
void get_have(int x,int y){
if(x== || y==) return ;
if(f[x][y]==f[tree[x].brother][y]) get_have(tree[x].brother,y);
else
for(int i=;i<y;i++)if(f[x][y]==f[tree[x].brother][i]+f[tree[x].child][y-i-]+tree[x].value){
get_have(tree[x].brother,i); get_have(tree[x].child,y-i-);
have[x]=true;
return ;
}
}
int main(){//freopen("ddd.in","r",stdin);
memset(tree,,sizeof(tree));
memset(have,,sizeof(have));
cin>>n>>m;
int _father;
for(int i=;i<=n;i++){
_father=read(); if(!_father) _father=n+; insert_tree(_father,i);//不设成0是因为还要判空
tree[i].value=read();
}
DP_tree(tree[n+].child,m);//不能从n+1开始,因为上面状态转移↑设定的是f[x][y]表示x自己和儿子和兄弟一起搞的最大值
cout<<f[tree[n+].child][m]<<endl;
get_have(tree[n+].child,m);
for(int i=;i<=n;i++)if(have[i]) cout<<i<<endl;
cout<<endl;
return ;
}