ALDS1_7_A Tree - Rooted Trees

Calendar Clock iconCalendar Clock icon

AOJ

# 目次

# 問題

# 解答

// C++ 14
#include <iostream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <math.h>

#define ll long long
#define Int int
#define loop(x, start, end) for(Int x = start; x < end; x++)
#define loopdown(x, start, end) for(int x = start; x > end; x--)
#define rep(n) for(int x = 0; x < n; x++)
#define span(a,x,y) a.begin()+x,a.begin()+y
#define span_all(a) a.begin(),a.end()
#define len(x) (x.size())
#define last(x) (*(x.end()-1))

using namespace std;
#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;
}

リモートフリーランス。ウェブサービス、スマホアプリエンジニア。
東アジアを拠点に世界を移動しながら活動してます!

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

コメント