mirror of
https://gitcode.com/Zengtudor/alg2025.git
synced 2025-09-03 16:51:43 +00:00
feat: 添加P2014题目解决方案实现动态规划算法
实现基于树形动态规划的课程选修问题解决方案,计算在限定课程数量下能获得的最大学分。使用深度优先搜索遍历课程依赖关系,并通过动态规划状态转移求解最优解。
This commit is contained in:
parent
52b2321a96
commit
5e23f17133
55
src/8/29/P2014.cpp
Normal file
55
src/8/29/P2014.cpp
Normal file
@ -0,0 +1,55 @@
|
||||
/*
|
||||
|
||||
dp[i][j]=修第i个课程时(以i为根),总共选修了j门课程学习的最大学分是多少
|
||||
|
||||
dp[u][j]=max(
|
||||
dp[u][j],
|
||||
dp[v][1~j-1]+v[u]
|
||||
)
|
||||
|
||||
*/
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <iostream>
|
||||
#include <istream>
|
||||
#include <vector>
|
||||
using ll = int64_t;
|
||||
|
||||
ll n,m;
|
||||
std::vector<ll> f,val;
|
||||
std::vector<std::vector<ll>> dp;
|
||||
std::vector<std::vector<ll>> edg;
|
||||
|
||||
static inline void dfs(const ll u){
|
||||
dp[u][1]=val[u];
|
||||
for(auto v:edg[u]){
|
||||
dfs(v);
|
||||
for(ll i=m;i>=1;--i){
|
||||
for(ll j=i-1;j>=1;--j){
|
||||
dp[u][i]=std::max(
|
||||
dp[u][i],
|
||||
dp[v][j]+dp[u][i-j]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(){
|
||||
std::iostream::sync_with_stdio(false);
|
||||
std::cin.tie(nullptr);
|
||||
|
||||
std::cin>>n>>m;
|
||||
++m;
|
||||
f.resize(n+1);
|
||||
val.resize(n+1);
|
||||
dp.resize(n+1,std::vector<ll>(m+1));
|
||||
edg.resize(n+1);
|
||||
for(ll i=1;i<=n;++i){
|
||||
std::cin>>f[i]>>val[i];
|
||||
edg[f[i]].push_back(i);
|
||||
}
|
||||
dfs(0);
|
||||
std::cout<<dp[0][m]<<"\n";
|
||||
}
|
Loading…
Reference in New Issue
Block a user