Aizu Online Judge(AOJ)の過去問から、その提出コードの解答例です。
・問題 "Rooted Trees"
https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_7_A
・根付き木
僕が作成、提出したコードは、以下のとおりです。
Aizu Online Judge in C++ #ALDS1_7_A : Rooted Trees
/* Aizu Online Judge in C++ #ALDS1_7_A : Rooted Trees https://onlinejudge.u-aizu.ac.jp/problems/ALDS1_7_A 提出コードの解答例 https://neguse-atama.hatenablog.com */ #include<bits/stdc++.h> using namespace std; struct N{int p,l,r;}; N t[100000]; int n,d,k,c,r,i,j,m,o,D[100000]; void f(int r,int d){ D[r]=d; if(~t[r].r){ f(t[r].r,d); } if(~t[r].l){ f(t[r].l,d+1); } } int main(void){ for(cin>>n;j<n;j++){ t[j].p=t[j].l=t[j].r=-1; } for(;i++<n;){ for(cin>>d>>k,j=0;j<k;r=c){ cin>>c; t[c].p=d; ((j++) ? t[r].r=c : t[d].l=c); } } for(;m<n;m++){ if(!~t[m].p){ f(m,0); } } for(;o<n;o++){ printf("node %d: parent = %d, depth = %d, ",o,t[o].p,D[o]); printf(~t[o].p ? ~t[o].l ? "internal node, [" : "leaf, [" : "root, ["); for(i=0,j=t[o].l;~j;){ printf(i++ ? ", %d" : "%d",j),j=t[j].r; } printf("]\n"); } return 0; }
設問の出典は、プログラミング問題のオンライン採点システム「Aizu Online Judge(AOJ)」です。
http://judge.u-aizu.ac.jp/onlinejudge/