Codeforces Round #387 (Div. 2), problem: (E) Comments Solution in C/C++
#include <stdio.h> #include <string.h> #include <stdlib.h> #define N 1000000 int ccnt; struct comment { char *s; int d, i; } cc[N]; char *ss[N]; int parse(int d, int i) { int k = atoi(ss[i + 1]); cc[ccnt].s = strdup(ss[i]); cc[ccnt].d = d; cc[ccnt++].i = i; i += 2; while (k-- > 0) i = parse(d + 1, i); return i; } int compare(const void *a, const void *b) { struct comment *pa = (struct comment *) a; struct comment *pb = (struct comment *) b; return pa->d != pb->d ? pa->d - pb->d : pa->i - pb->i; } int main() { int k_, k, i, j, m; static char s[N + 1], *t; scanf("%s", s); t = strtok(s, ","); for (k_ = 0; t != NULL; ss[k_++] = strdup(t), t = strtok(NULL, ",")) ; k = k_ / 2; ccnt = 0; for (i = 0; i < k_; i = parse(0, i)) ; qsort(cc, k, sizeof(*cc), compare); m = cc[k - 1].d + 1; printf("%d\n", m); for (i = 0, j = 0; i < m; i++) { while (j < k && cc[j].d == i) { printf("%s ", cc[j].s); j++; } printf("\n"); } return 0; }