Codeforces Round #419 (Div. 1), problem: (C) Karen and Supermarket Solution In C/C++

#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
const int N=5010;
int n,m,c[N],d[N],fa[N];
int w[N],head[N],next[N];
void add(int f,int t){
static int cnt=0;
w[++cnt]=t;
next[cnt]=head[f];
head[f]=cnt;
}
int f[N][N],g[N][N],size[N];
//f[i][j],g[i][j]表示在子树i中买j件物品的最小代价
//其中g要求购买从根到i的物品
void dfs(int x){
for (int i=1;i<=n;i++) f[x][i]=g[x][i]=1e9+1;
g[x][0]=g[x][1]=c[x]-d[x];
f[x][1]=c[x];
size[x]=1;
for (int i=head[x];i;i=next[i]){
int v=w[i];
dfs(v);
for (int a=size[x];a>=0;a–)
for (int b=1;b<=size[v];b++){
f[x][a+b]=min(f[x][a+b],f[x][a]+f[v][b]);
g[x][a+b]=min(g[x][a+b],g[x][a]+min(f[v][b],g[v][b]));
}
size[x]+=size[v];
}
}
int main()
{
scanf(“%d%d”,&n,&m);
scanf(“%d%d”,&c[1],&d[1]);
for (int i=2;i<=n;i++){
scanf(“%d%d%d”,&c[i],&d[i],&fa[i]);
add(fa[i],i);
}
dfs(1);
int ans=0;
for (int i=1;i<=n;i++)
if (m>=f[1][i]||m>=g[1][i]) ans=i;
printf(“%d\n”,ans);
return 0;
}

Knicks, NYC Officials Spar...

A heated political and sports dispute has erupted in...

curl-programming-lang 1.0.2

Introduction to curl-programming-lang 1.0.2 The open-source developer ecosystem continues to...

Why Everyone is Obsessed with the Smart Plug Wifi Outlet

Are you tired of dealing with everyday frustrations that slow down your routine? We've all been...

Knicks, NYC Officials Spar Over MSG Watch Parties

A heated political and sports dispute has erupted in New York City, as Madison Square Garden (MSG) Entertainment and local public officials trade sharp...

Why Everyone is Obsessed with the Under Desk Foot Rest

Are you tired of dealing with everyday frustrations that slow down your routine? We've all been...

Why Everyone is Obsessed with the Rug Gripper Pads

Are you tired of dealing with everyday frustrations that slow down your routine? We've all been...

curl-programming-lang 1.0.2

Introduction to curl-programming-lang 1.0.2 The open-source developer ecosystem continues to thrive with the introduction of innovative tools designed to simplify software creation. A fascinating new...

Why Everyone is Obsessed with the Blind Spot Mirrors

Are you tired of dealing with everyday frustrations that slow down your routine? We've all been...

Why Everyone is Obsessed with the Magnetic Spice Rack

Are you tired of dealing with everyday frustrations that slow down your routine? We've all been...

Why Everyone is Obsessed with the Webcam Cover Slide

Are you tired of dealing with everyday frustrations that slow down your routine? We've all been...

Why Everyone is Obsessed with the Magnetic Cabinet Locks

Are you tired of dealing with everyday frustrations that slow down your routine? We've all been...