fork download
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <vector>
  4. #include <string>
  5. #include <sstream>
  6. #include <algorithm>
  7. using namespace std;
  8.  
  9. class Klasemen {
  10. private:
  11. unordered_map<string, int> clubScoreMap;
  12. bool changed;
  13. vector<string> cachedKlasemen;
  14.  
  15. void sortKlasemen() {
  16. sort(cachedKlasemen.begin(), cachedKlasemen.end(),
  17. [&](const string& a, const string& b) {
  18. if (clubScoreMap[a] != clubScoreMap[b]) {
  19. return clubScoreMap[a] > clubScoreMap[b];
  20. }
  21. return a < b;
  22. }
  23. );
  24. }
  25.  
  26. public:
  27. Klasemen(vector<string> clubs) {
  28. for (string s : clubs) {
  29. clubScoreMap[s] = 0;
  30. cachedKlasemen.push_back(s);
  31. }
  32.  
  33. changed = true;
  34. }
  35.  
  36. void catatPermainan(string klubKandang, string klubTandang, string skor) {
  37. vector<int> points;
  38.  
  39. stringstream ss(skor);
  40. string poin;
  41.  
  42. while (getline(ss, poin, ':')) {
  43. points.push_back(stoi(poin));
  44. }
  45.  
  46. if (points[0] > points[1]) {
  47. clubScoreMap[klubKandang] += 3;
  48. } else if (points[0] < points[1]) {
  49. clubScoreMap[klubTandang] += 3;
  50. } else {
  51. clubScoreMap[klubKandang] += 1;
  52. clubScoreMap[klubTandang] += 1;
  53. }
  54. changed = true;
  55. }
  56.  
  57. vector<string> cetakKlasemen() {
  58. if (changed) {
  59. sortKlasemen();
  60. changed = false;
  61. }
  62. return cachedKlasemen;
  63. }
  64.  
  65. string ambilPeringkat(int nomorPeringkat) {
  66. if (changed) {
  67. sortKlasemen();
  68. changed = false;
  69. }
  70. if(nomorPeringkat <= 0 || nomorPeringkat > cachedKlasemen.size()){
  71. return "Peringkat tidak sesuai";
  72. }
  73. return cachedKlasemen[nomorPeringkat - 1];
  74. }
  75. };
  76.  
  77. int main() {
  78. Klasemen klasemen({"Liverpool", "Chelsea", "Arsenal"});
  79.  
  80. klasemen.catatPermainan("Arsenal", "Liverpool", "2:1");
  81. klasemen.catatPermainan("Arsenal", "Chelsea", "1:1");
  82. klasemen.catatPermainan("Chelsea", "Arsenal", "0:3");
  83. klasemen.catatPermainan("Chelsea", "Liverpool", "3:2");
  84. klasemen.catatPermainan("Liverpool", "Arsenal", "2:2");
  85. klasemen.catatPermainan("Liverpool", "Chelsea", "0:0");
  86.  
  87. vector<string> hasil = klasemen.cetakKlasemen();
  88.  
  89. cout << "Klasemen:" << endl;
  90. for (const string& club : hasil) {
  91. cout << club << endl;
  92. }
  93.  
  94. cout << endl;
  95. cout << klasemen.ambilPeringkat(2) << endl;
  96.  
  97. return 0;
  98. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
Klasemen:
Arsenal
Chelsea
Liverpool

Chelsea