Pagini recente » Cod sursa (job #1694536) | Cod sursa (job #3042136) | Cod sursa (job #2523818) | Cod sursa (job #2028362) | Cod sursa (job #103795)
Cod sursa(job #103795)
#include <stdio.h>
#include <stdlib.h>
#define M 100001
typedef struct _lnod {int nn; struct _lnod *urm;} lnod;
typedef struct _nod {int v; int t; int V; int niv; lnod *f;} nod;
int q[M],sz=sizeof(lnod),nrdiv,dim;
nod a[M];
int fc(const void *x,const void *y)
{
return a[*(int *)y].V-a[*(int *)x].V;
}
void proces(int r)
{
int i=0,v[M];
lnod *p;
if(a[r].V>dim)
{
p=a[r].f; while(p) {v[i++]=p->nn; p=p->urm;}
qsort(v,i,sizeof(int),fc);
for(i=0;a[r].V>dim;i++)
{
a[r].V-=a[v[i]].V;
nrdiv++;
}
}
a[a[r].t].V+=a[r].V;
}
int main()
{
FILE *fi,*fo;
int i,k,n,rad=0,iq,sq; lnod *p;
fi=fopen("mese.in","rt");
fscanf(fi,"%d %d",&n,&dim);
for(i=1;i<=n;i++)
{
fscanf(fi,"%d %d",&k, &a[i].v);
a[i].t=k;
a[i].V=a[i].v;
if(!k) rad=i;
else
{
p=(lnod *)malloc(sz);
p->nn=i;
p->urm=a[k].f;
a[k].f=p;
}
}
fclose(fi);
q[1]=rad;
iq=sq=1;
while(iq<=sq)
{
k=q[iq];
a[k].niv=a[a[k].t].niv+1;
p=a[k].f;
while(p)
{
q[++sq]=p->nn;
p=p->urm;
}
iq++;
}
for(i=n;i>0;i--) proces(q[i]);
fo=fopen("mese.out","wt");
fprintf(fo,"%d\n",nrdiv+1);
fclose(fo);
return 0;
}