fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. enum class type {
  6. vector_type,
  7. integer_type
  8. };
  9.  
  10. // Object can either be an Integer or Vector<Object>
  11. class Object {
  12. public:
  13. type type_;
  14. vector<Object> vec_;
  15. int num_;
  16.  
  17. Object(): type_(type::integer_type)
  18. {
  19. }
  20.  
  21. Object(const Object& other): type_(other.type_)
  22. {
  23. if(other.type_ == type::vector_type)
  24. vec_ = other.vec_;
  25. else
  26. num_ = other.num_;
  27. }
  28.  
  29. //Object(const vector<int> &vec): type_(type::vector_type) {
  30. // for (int i = 0; i < vec.size(); i++) {
  31. // vec_.push_back(Object(vec[i]));
  32. // }
  33. //}
  34.  
  35. Object(const vector<int> &vec): type_(type::vector_type),
  36. vec_(vec.begin(), vec.end()) {
  37. }
  38.  
  39. Object& operator=(const Object &other) {
  40. type_ = other.type_;
  41. if(other.type_ == type::vector_type)
  42. vec_ = other.vec_;
  43. else
  44. num_ = other.num_;
  45. return *this;
  46. }
  47.  
  48. Object(const vector<Object> &vec) {
  49. type_ = type::vector_type;
  50. vec_ = vec;
  51. }
  52.  
  53. Object(int num): type_(type::integer_type),
  54. num_(num)
  55. {
  56. }
  57. };
  58.  
  59. int getSum_internal(Object &o, int &sum) {
  60. for (int i = 0; i < o.vec_.size(); i++) {
  61. if (o.vec_[i].type_ == type::integer_type) {
  62. sum += o.vec_[i].num_;
  63. }
  64.  
  65. if (o.vec_[i].type_ == type::vector_type) {
  66. getSum_internal(o.vec_[i], sum);
  67. }
  68. }
  69. }
  70.  
  71. int getSum(Object &o) {
  72. int sum = 0;
  73. getSum_internal(o, sum);
  74. return sum;
  75. }
  76.  
  77. int main() {
  78. // to construct somth like that: [1,2, [3, [4,5], 6], 7]
  79. Object o1(vector<int>({1,2}));
  80. Object o2(vector<int>({3}));
  81. Object o3(vector<int>({4,5}));
  82. Object o4(vector<int>({6}));
  83. Object o5(vector<Object>({o2,o3,o4}));
  84. Object o6(vector<int>({7}));
  85. Object o(vector<Object>({o1,o5,o6}));
  86.  
  87. cout << getSum(o) << endl;
  88.  
  89. return 0;
  90. }
Success #stdin #stdout 0s 3464KB
stdin
Standard input is empty
stdout
28