fork download
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define ll long long
  5. #define pb push_back
  6. #define mp make_pair
  7. #define ff first
  8. #define ss second
  9. #define sc(x) scanf("%d",&x)
  10. #define scl(x) scanf("%lld",&x)
  11. #define pr(x) printf("%d\n",x)
  12. #define prl(x) printf("%lld\n",x)
  13. #define clr(x) memset(x, 0, sizeof(x))
  14.  
  15. const int N = 1e6+55;
  16.  
  17. vector< int > root;
  18. vector< int > adj[N];
  19. vector< pair<string, int> > v;
  20. vector<int>level[N];
  21. int lev[N], maxlev;
  22. bool vis[N];
  23. int point;
  24.  
  25. void dfs(int cur, int c) {
  26. if(cur==v.size()) return;
  27. vis[cur] = 1;
  28. lev[cur] = c;
  29. maxlev = max(maxlev, c);
  30. level[lev[cur]].pb(cur);
  31. for(int i=1 ; i<=v[cur].ss ; i++) {
  32. adj[cur].pb(point);
  33. ++point;
  34. dfs(point-1, c+1);
  35. }
  36. }
  37.  
  38. int main() {
  39. // freopen("Task.in","r",stdin);freopen("Task.out","w",stdout);
  40. std::ios::sync_with_stdio(false);
  41. cin.tie(NULL);
  42. cout.tie(NULL);
  43. string s;
  44. cin>>s;
  45. s = s+",";
  46. for(int i=0 ; i<s.size() ; i++) {
  47. string word = "";
  48. int child = 0;
  49. while(s[i]!=',') {
  50. word = word+s[i];
  51. ++i;
  52. }
  53. ++i;
  54. while(s[i]!=',') {
  55. child = child*10+s[i]-'0';
  56. ++i;
  57. }
  58. v.pb(mp(word, child));
  59. }
  60. point = 0;
  61. maxlev = 1;
  62. for(int i=0 ; i<v.size() ; i++) {
  63. if(vis[i]) continue;
  64. point = i+1;
  65. dfs(i, 1);
  66. root.pb(i);
  67. }
  68. cout<<(maxlev)<<"\n";
  69. for(int i=0 ; i<N ; i++) {
  70. if(level[i].size()==0) continue;
  71. for(vector<int>::iterator it=level[i].begin() ; it!=level[i].end() ; it++) cout<<v[*it].ff<<" ";
  72. cout<<("\n");
  73. }
  74. }
Success #stdin #stdout 0.01s 67008KB
stdin
A,3,B,2,C,0,D,1,E,0,F,1,G,0,H,1,I,1,J,0,K,1,L,0,M,2,N,0,O,1,P,0
stdout
4
A K M 
B F H L N O 
C D G I P 
E J