代码:
#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<vector>
#include<queue>
#include<stack>
#include<map>
using namespace std;
const int N=1500010;
struct E{
int val;
int next;
}edge[N];
int vis[N],head[N],dp[305],c,n,M,v[N];
void add(int x,int y){
edge[c].val=y;
edge[c].next=head[x];
head[x]=c;
c+=1;
}
int selMax(int x,int y){
return x>y?x:y;
}
int DFS(int root)
{
int all=0;
bool sign=false;
int cur[305];
for(int i=1;i<=M;i+=1){
cur[i]=dp[i]=-1;
}
cur[0]=dp[0]=0;
for(int i=head[root];i!=-1;i=edge[i].next)
{
int node=edge[i].val;
int state=DFS(node);
sign=true;
for(int x=all;x>=0;x--)
{
for(int y=1;y<=state;y+=1)
{
if(x+y>M) break;
cur[x+y]=selMax(cur[x+y],dp[y]+cur[x]);
}
}
all+=state;
}
if(sign==false) all+=1;
cur[1]=selMax(cur[1],v[root]);
for(int i=0;i<=M;i+=1)
dp[i]=cur[i];
return all;
}
int main()
{
while(~scanf("%d %d",&n,&M))
{
memset(head,-1,sizeof(head));
c=0;
int root;
for(int i=1;i<=n;i+=1)
{
int u;
scanf("%d%d",&u,&v[i]);
if(u==0) root=u;
add(u,i);
}
DFS(root);
if(dp[M]==-1)
printf("impossible\n");
else
printf("%d\n",dp[M]);
}
return 0;
}