zoukankan      html  css  js  c++  java
  • joyOI 选课 【树形dp + 背包dp】

    题目链接

    选课

    题解

    基础背包树形dp

    #include<iostream>
    #include<cstdio>
    #include<cmath>
    #include<cstring>
    #include<algorithm>
    #define LL long long int
    #define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
    #define REP(i,n) for (int i = 1; i <= (n); i++)
    #define BUG(s,n) for (int i = 1; i <= (n); i++) cout<<s[i]<<' '; puts("");
    #define cls(s) memset(s,-0x3f3f3f3f,sizeof(s))
    using namespace std;
    const int maxn = 305,maxm = 100005,INF = 1000000000;
    inline int read(){
    	int out = 0,flag = 1; char c = getchar();
    	while (c < 48 || c > 57){if (c == '-') flag = -1; c = getchar();}
    	while (c >= 48 && c <= 57){out = (out << 3) + (out << 1) + c - 48; c = getchar();}
    	return out * flag;
    }
    int h[maxn],ne = 1;
    struct EDGE{int to,nxt;}ed[maxm];
    inline void build(int u,int v){
    	ed[ne] = (EDGE){v,h[u]}; h[u] = ne++;
    }
    int n,m,val[maxn],f[maxn][maxn],fa[maxn];;
    void dfs(int u){
    	f[u][0] = 0;
    	Redge(u){
    		dfs(to = ed[k].to);
    		for (int i = m; i >= 0; i--)
    			for (int j = i; j >= 0; j--)
    				f[u][i] = max(f[u][i],f[u][i - j] + f[to][j]);
    	}
    	if (u != 0)
    		for (int i = m; i; i--)
    			f[u][i] = f[u][i - 1] + val[u];
    }
    int main(){
    	cls(f);
    	n = read(); m = read();
    	REP(i,n){
    		fa[i] = read();
    		val[i] = read();
    		build(fa[i],i);
    	}
    	dfs(0);
    	int ans = 0;
    	for (int i = 0; i <= m; i++) ans = max(ans,f[0][i]);
    	printf("%d
    ",ans);
    	return 0;
    }
    
    
  • 相关阅读:
    四则运算(判断正误)
    Right-BICEP要求四则2的测试用例
    《构建之法》阅读笔记02
    第二周的学习进度
    四则运算(升级)
    构建之法阅读笔记01
    新手安装使用codeblocks
    新的一年你该如何起飞
    中国国家图书馆 注册后可以免费使用 维普等多个数据库资源
    c++学籍管理系统v1.10
  • 原文地址:https://www.cnblogs.com/Mychael/p/9018704.html
Copyright © 2011-2022 走看看