fork download
  1. #include <iostream>
  2. #include <algorithm>
  3. #include <vector>
  4. #include <map>
  5. #include <set>
  6.  
  7. using namespace std;
  8.  
  9. struct ChildInfo
  10. {
  11. int id;
  12. double gram;
  13. };
  14.  
  15. // Custom functor to compare doubles.
  16. struct DoubleCompare
  17. {
  18. bool operator()(double x1, double x2)
  19. {
  20. static double tolerance = 1.0E-10; // Pick something else if this doesn't work.
  21. // If the numbers are almost equal.
  22. return ( fabs(x2-x1) > tolerance && x1 < x2);
  23. }
  24. };
  25.  
  26. // Function to compare two ChildInfo to insert them into a set.
  27. bool operator < (const ChildInfo& lhs, const ChildInfo& rhs) { return lhs.id < rhs.id; }
  28.  
  29. std::ostream& operator<<(std::ostream& str, const ChildInfo& ci) {
  30. str << " " << ci.id << " gram " << ci.gram << "\n";
  31. return str;
  32. }
  33.  
  34. // Read the info for one child.
  35. void input(vector<ChildInfo> &v)
  36. {
  37. ChildInfo newInfo;
  38.  
  39. cin >> newInfo.id >> newInfo.gram;
  40. v.push_back(newInfo);
  41. }
  42.  
  43. // Compute the mapped info from the vector of ChildInfo
  44. void computeMappedInfo(vector<ChildInfo> const& vinfo,
  45. std::map<double, std::set<ChildInfo>, DoubleCompare>& mappedInfo)
  46. {
  47. // Separate them into sets first.
  48. for ( ChildInfo const& info : vinfo )
  49. {
  50. mappedInfo[info.gram].insert(info);
  51. }
  52.  
  53. // Divide the grams in the set.
  54. for ( auto& item : mappedInfo )
  55. {
  56. // The set can't be changed in place.
  57. // Create a new set and replace the old set with the new set.
  58.  
  59. std::set<ChildInfo> newSet;
  60. size_t s = item.second.size();
  61. for ( auto info : item.second )
  62. {
  63. info.gram /= s;
  64. newSet.insert(info);
  65. }
  66. mappedInfo[item.first] = newSet;
  67. }
  68. }
  69.  
  70. // Display the mapped info.
  71. void display(std::map<double, std::set<ChildInfo>, DoubleCompare> const& mappedInfo)
  72. {
  73. for ( auto const& item : mappedInfo )
  74. {
  75. for ( auto& info : item.second )
  76. {
  77. std::cout << info << std::endl;
  78. }
  79. }
  80. }
  81.  
  82. int main()
  83. {
  84. int childNum = 0;
  85. cin >> childNum;
  86.  
  87. std::vector <ChildInfo> info;
  88.  
  89. for (int i = 0; i < childNum; ++i) {
  90. input(info);
  91. }
  92.  
  93. std::map<double, std::set<ChildInfo>, DoubleCompare> mappedInfo;
  94. computeMappedInfo(info, mappedInfo);
  95. display(mappedInfo);
  96.  
  97. return 0;
  98. }
  99.  
Success #stdin #stdout 0s 3480KB
stdin
8
1 1000
2 1000
3 1000
4 500
5 600
7 800
8 800
stdout
 4 gram 500

 5 gram 600

 7 gram 400

 8 gram 400

 1 gram 333.333

 2 gram 333.333

 3 gram 333.333