Cod sursa(job #2273170)

Utilizator andrei.arnautuAndi Arnautu andrei.arnautu Data 31 octombrie 2018 09:48:51
Problema Sortare Scor 5
Compilator cpp-64 Status done
Runda Arhiva de probleme Marime 1.43 kb
/**
  *  Worg
  */
#include <cstdio>
#include <cassert>
#include <algorithm>
FILE *fin = freopen("sortare.in", "r", stdin); FILE *fout = freopen("sortare.out", "w", stdout);

const int MAX_N = 5000 + 5;

//-------- Data --------
int n;
int a[MAX_N], b[MAX_N], c[MAX_N];

int ans[MAX_N];
int h;
//-------- --------

void ReadInput() {
  scanf("%d", &n);

  for (int i = 2; i <= n; i++) {
    scanf("%d%d%d", &a[i], &b[i], &c[i]);
  }
}

void Place(int position, int value) {
  int index = 0;
  while (position > 0) {
    index++;

    if (ans[index] == 0) {
      position--;
    }
  }

  ans[index] = value;
}

void Solve(int size) {
  if(size <= 0) {
    return;
  }

  h++;
  if (size == 1) {
    Place(1, 1); return;
  }

  if (a[size] != b[size] && a[size] != c[size] && b[size] != c[size]) {  ///  Case 1 : they are all distinct
    Place(c[size], size);
    Place(b[size], size - 1);

    Solve(size - 2);
  } else {  ///  Case 2 : we have at least two equal elements
    if (a[size] == b[size]) {
      Place(a[size], size);
    } else if (b[size] == c[size]) {
      Place(b[size], size);
    }

    Solve(size - 1);
  }
}

void PrintOutput() {
  printf("%d\n", h);

  for (int i = 1; i <= n; i++) {
    assert(1 <= ans[i] && ans[i] <= n);
    for (int j = 1; j < i; j++) {
      assert(ans[i] != ans[j]);
    }
  }

  for (int i = 1; i <= n; i++) {
    printf("%d ", ans[i]);
  }
}

int main() {
  ReadInput();

  Solve(n);

  PrintOutput();
  return 0;
}