fork download
  1. #include <iostream>
  2. #include <map>
  3. #include <set>
  4. #include <cstdio>
  5. #include <algorithm>
  6. #include <cmath>
  7. #include <string>
  8. #include <climits>
  9. #include <vector>
  10. #include <cstdlib>
  11. #include <sstream>
  12. using namespace std;
  13.  
  14. #define MOD 1000000007
  15. #define pb push_back
  16. #define mp make_pair
  17. #define F first
  18. #define S second
  19. #define N 50005
  20. #define PII pair<int,int>
  21.  
  22. pair<int,string>p[N];
  23.  
  24. struct node
  25. {
  26. int index;
  27. node *left,*right;
  28. node(int i, node* p1, node* p2)
  29. {
  30. index=i;
  31. left=p1;
  32. right=p2;
  33. }
  34. };
  35.  
  36. void preorder(node * root)
  37. {
  38. if(root)
  39. {
  40. cout<<"(";
  41. preorder(root->left);
  42. cout<<p[root->index].S<<"/"<<p[root->index].F;
  43. preorder(root->right);
  44. cout<<")";
  45. }
  46.  
  47. }
  48.  
  49. void build(node *root, int i) //Binary search tree
  50. {
  51. node *temp = new node(i,NULL,NULL);
  52. node *t = root;
  53. while(t)
  54. {
  55. if(p[i].S<p[root->index].S)
  56. {
  57. if(t->left) t = t->left;
  58. else {t->left=temp; return;}
  59. }
  60. else
  61. {
  62. if(t->right) t = t->right;
  63. else {t->right=temp; return;}
  64. }
  65. }
  66.  
  67. }
  68.  
  69. int main()
  70. {
  71. ios_base::sync_with_stdio(0);
  72. cin.tie(0);
  73. //cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
  74.  
  75.  
  76. #ifndef ONLINE_JUDGE
  77. freopen("inp.txt","r",stdin);
  78. freopen("out.txt","w",stdout);
  79. #endif
  80.  
  81. int n,x,i,j;
  82. cin>>n;
  83.  
  84. string s;
  85.  
  86. while(n)
  87. {
  88. for(i=0;i<n;i++)
  89. {
  90. cin>>s;
  91. int l = s.size();
  92. string t=""; j=0; x=0;
  93. while(s[j]!='/') { t+=s[j]; j++;}
  94. j++;
  95. while(j<l) {x = x*10+(s[j]-'0'); j++;}
  96. p[i] = make_pair(x,t);
  97. }
  98. sort(p,p+n);
  99.  
  100. node *root = new node(n-1,NULL,NULL);
  101.  
  102. for(i=n-2;i>=0;i--) build(root,i);
  103.  
  104. preorder(root);
  105. cout<<endl;
  106. cin>>n;
  107. }
  108.  
  109. return 0;
  110. }
Success #stdin #stdout 0s 18024KB
stdin
7 a/7 b/6 c/5 d/4 e/3 f/2 g/1
7 a/1 b/2 c/3 d/4 e/5 f/6 g/7
7 a/3 b/6 c/4 d/7 e/2 f/5 g/1
0
stdout
(a/7(b/6(c/5(d/4(e/3(f/2(g/1)))))))
(((((((a/1)b/2)c/3)d/4)e/5)f/6)g/7)
((((a/3)c/4)b/6)d/7(f/5(e/2(g/1))))