AOJ

# # 解答

#define MAX 100001
#define NIL -1

struct Node { int parent, left, right; };

void print(int i, Node arr[], int ds[]) {
cout << "node " << i << ": ";
cout << "parent = " << arr[i].parent;
cout << ", depth = " << ds[i];
cout << ", ";

if (arr[i].parent == NIL) cout << "root";
else if (arr[i].left == NIL) cout << "leaf";
else cout << "internal node";
cout << ", [";

if (arr[i].left != NIL) {
int current = arr[i].left;
cout << current;

while (arr[current].right != NIL) {
current = arr[current].right;
cout << ", " << current;
}
}
cout << "]" << endl;
}

void depth(int n, int d, Node nodes[], int ds[]) {
ds[n] = d;
if (nodes[n].right != NIL) depth(nodes[n].right, d, nodes, ds);
if (nodes[n].left != NIL) depth(nodes[n].left, d+1, nodes, ds);
}

int main() {
int n, id, k, c, root;
Node T[MAX];
int D[MAX];

cin >> n;
for (int i=0; i<n; i++) T[i].parent = T[i].left = T[i].right = NIL;

for (int i = 0; i < n; i++) {
cin >> id >> k;

int left;
for (int j = 0; j < k; j++) {
cin >> c;
if (j == 0) T[id].left = c;
else T[left].right = c;
T[c].parent = id;
left = c;
}
}

for (int i=0; i<n; i++) {
if (T[i].parent == NIL) {
root = i;
break;
}
}

depth(root, 0, T, D);

for (int i=0; i<n; i++) print(i, T, D);
return 0;
}


リモートフリーランス。ウェブサービス、スマホアプリエンジニア。

お仕事のご依頼・お問い合わせはこちら