irv.cpp 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. #include <string>
  2. #include <vector>
  3. #include <list>
  4. #include <map>
  5. #include <iostream>
  6. using namespace std;
  7. int main ( )
  8. {
  9. string s;
  10. list < string > vote;
  11. vector < list < string > > votes;
  12. map < string, size_t > candidates;
  13. while ( true )
  14. {
  15. getline ( cin, s );
  16. if ( cin.eof ( ) )
  17. {
  18. if ( !vote.empty ( ) ) votes.push_back ( vote );
  19. break;
  20. }
  21. if ( s == "vote:" )
  22. {
  23. if ( !vote.empty ( ) )
  24. {
  25. votes.push_back ( vote );
  26. vote.clear ( );
  27. }
  28. }
  29. else
  30. {
  31. candidates.insert ( map < string, size_t >::value_type ( s, 0 ) );
  32. vote.push_back ( s );
  33. }
  34. }
  35. bool winner = false;
  36. size_t min_votes;
  37. map < string, size_t >::iterator c_iter, c_next;
  38. vector < list < string > >::iterator vl_iter;
  39. while ( !winner )
  40. {
  41. c_iter = candidates.begin ( );
  42. while ( c_iter != candidates.end ( ) )
  43. {
  44. cout << "clearing votes for " << c_iter->first << endl;
  45. c_iter->second = 0;
  46. ++c_iter;
  47. }
  48. vl_iter = votes.begin ( );
  49. while ( vl_iter != votes.end ( ) )
  50. {
  51. list < string >::iterator v_iter ( vl_iter->begin ( ) );
  52. while ( v_iter != vl_iter->end ( ) )
  53. {
  54. c_iter = candidates.find ( *v_iter );
  55. if ( c_iter != candidates.end ( ) )
  56. {
  57. ++( c_iter->second );
  58. break;
  59. }
  60. ++v_iter;
  61. }
  62. ++vl_iter;
  63. }
  64. c_iter = candidates.begin ( );
  65. min_votes = c_iter->second;
  66. winner = true;
  67. while ( c_iter != candidates.end ( ) )
  68. {
  69. cout << c_iter->first << " has a total of " << c_iter->second << " votes" << endl;
  70. if ( c_iter->second != min_votes )
  71. {
  72. winner = false;
  73. }
  74. if ( c_iter->second < min_votes )
  75. {
  76. min_votes = c_iter->second;
  77. }
  78. ++c_iter;
  79. }
  80. if ( winner )
  81. {
  82. if ( candidates.size ( ) > 1 )
  83. {
  84. cout << endl << "TIE, WINNERS WERE:" << endl;
  85. }
  86. else
  87. {
  88. cout << endl << "WINNER:" << endl;
  89. }
  90. }
  91. c_iter = candidates.begin ( );
  92. while ( c_iter != candidates.end ( ) )
  93. {
  94. c_next = c_iter;
  95. ++c_next;
  96. if ( winner )
  97. {
  98. cout << c_iter->first << endl;
  99. }
  100. else if ( c_iter->second == min_votes )
  101. {
  102. cout << c_iter->first << " has been removed from the running" << endl;
  103. candidates.erase ( c_iter );
  104. }
  105. c_iter = c_next;
  106. }
  107. }
  108. return 0;
  109. }
粤ICP备19079148号