E79 树上背包 P1270 “访问”美术馆

视频链接:E79 树上背包 P1270 “访问”美术馆_哔哩哔哩_bilibili

 

 

 

P1270 “访问”美术馆 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

复制代码
// 树上背包 O(2000*6000)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int N=6005;
int head[N],idx;
struct E{int v,t,ne;}e[N];
void add(int u,int v,int t){
  e[++idx]={v,t,head[u]};
  head[u]=idx;
}
int n,tot,ans,f[N][N],sz[N];

void build(int u,int fa){
  int tim,pic;
  scanf("%d%d",&tim,&pic);
  add(fa,u,tim*2);
  if(!pic){
    build(++tot,u);
    build(++tot,u);
  }
  else while(pic--)add(u,0,5);
}
void dfs(int u){
  for(int i=head[u];i;i=e[i].ne){
    int v=e[i].v,t=e[i].t;
    dfs(v);
    sz[u]+=sz[v]+t;
    for(int j=min(n,sz[u]);j>=t;j--)
      for(int k=0;k<=min(j-t,sz[v]);k++)
        f[u][j]=max(f[u][j],f[u][j-k-t]+f[v][k]);
  }
}
int main(){
  scanf("%d",&n);n--;
  tot=1;
  build(++tot,1);
  f[0][0]=1; //每个叶子有一幅画
  dfs(1);
  printf("%d\n",f[1][n]);
}
复制代码

 

P3360 偷天换日 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn)

复制代码
// 树上背包 O(9000*600)
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

const int N=10005;
int head[N],idx;
struct E{int v,t,w,ne;}e[N];
void add(int u,int v,int t,int w){
  e[++idx]={v,t,w,head[u]};
  head[u]=idx;
}
int n,tot,ans,f[N][N],sz[N];

void build(int u,int fa){
  int t,x,w,c;
  scanf("%d%d",&t,&x);
  add(fa,u,t*2,0);
  if(!x){
    build(++tot,u);
    build(++tot,u);
  }
  else
    while(x--){
      scanf("%d%d",&w,&c);
      add(u,0,c,w);
    }
}
void dfs(int u){
  for(int i=head[u];i;i=e[i].ne){
    int v=e[i].v,t=e[i].t;
    if(v==0) f[0][0]=e[i].w;
    dfs(v);
    sz[u]+=sz[v]+t;
    for(int j=min(n,sz[u]);j>=t;j--)
      for(int k=0;k<=min(j-t,sz[v]);k++)
        f[u][j]=max(f[u][j],f[u][j-k-t]+f[v][k]);
  }
}
int main(){
  scanf("%d",&n),n--;
  tot=1;
  build(++tot,1);
  dfs(1);
  printf("%d\n",f[1][n]);
}
复制代码

 

posted @   董晓  阅读(122)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示