Cod sursa(job #1735259)

Utilizator cella.florescuCella Florescu cella.florescu Data 29 iulie 2016 13:16:46
Problema Zvon Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.43 kb
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 100000
#define NECALC -2000000000

using namespace std;

int vf[MAXN], urm[MAXN], lst[MAXN+1], timpmin[MAXN+1], aux[MAXN], much;

inline int maximum(int a, int b){
  if(a>b)
    return a;
  return b;
}

inline void add(int x, int y){
  vf[++much]=y;
  urm[much]=lst[x];
  lst[x]=much;
}

int cmp(int A, int B){
  return A>B;
}

int tpmin(int nod){
  if(timpmin[nod]==NECALC)
    if(lst[nod]==0)
      timpmin[nod]=0;
    else{
      int p=lst[nod], n=0;
      while(p){
        tpmin(vf[p]);
        p=urm[p];
      }
      p=lst[nod];
      while(p){
        aux[n++]=timpmin[vf[p]];
        p=urm[p];
      }
      sort(aux, aux+n, cmp);
      int maxim=NECALC;
      for(p=0; p<n; p++)
        maxim=maximum(maxim, aux[p]+p+1);
      timpmin[nod]=maxim;
    }
  return timpmin[nod];
}

int main()
{
    FILE *fin, *fout;
    int t, n, i, a, b;
    fin=fopen("zvon.in", "r");
    fscanf(fin, "%d", &t);
    fout=fopen("zvon.out", "w");
    for(t; t>0; t--){
      much=0;
      memset(lst, 0, sizeof(lst));
      memset(urm, 0, sizeof(urm));
      for(i=0; i<=MAXN; i++)
        timpmin[i]=NECALC;
      fscanf(fin, "%d", &n);
      for(i=1; i<n; i++){
        fscanf(fin, "%d%d", &a, &b);
        add(a, b);
      }
      fprintf(fout, "%d\n", tpmin(1));
    }
    fclose(fin);
    fclose(fout);
    return 0;
}