解法一:队列

将老鼠加入队列,从队列头取出分组比较,将胜者加入队列尾,直到决出冠军。
败者 rank = 本轮分组数+1

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. class Mice {
  4. public:
  5. int weight;
  6. int rank;
  7. };
  8. int main() {
  9. int N, M;
  10. cin >> N >> M;
  11. Mice mices[N];
  12. for (int i = 0; i < N; ++i) {
  13. cin >> mices[i].weight;
  14. }
  15. deque<Mice *> playList;
  16. for (int i = 0, tmp; i < N; ++i) {
  17. cin >> tmp;
  18. playList.emplace_back(&mices[tmp]);
  19. }
  20. while (playList.size() > 1) {
  21. int size = playList.size();
  22. int groupNum = size / M + (size % M > 0);
  23. vector<Mice *> matchList;
  24. for (int i = 0; i < size; ++i) {
  25. if (matchList.size() < M) {
  26. matchList.emplace_back(playList.front());
  27. playList.pop_front();
  28. }
  29. if (matchList.size() == M) {
  30. int max = -1;
  31. for (auto &it:matchList) {
  32. if (it->weight > max) {
  33. max = it->weight;
  34. }
  35. }
  36. for (auto &it:matchList) {
  37. if (it->weight < max) {
  38. it->rank = groupNum + 1;
  39. } else {
  40. playList.emplace_back(it);
  41. }
  42. }
  43. matchList.clear();
  44. }
  45. }
  46. // 最后一组
  47. if (!matchList.empty()) {
  48. int max = -1;
  49. for (auto &it:matchList) {
  50. if (it->weight > max) {
  51. max = it->weight;
  52. }
  53. }
  54. for (auto &it:matchList) {
  55. if (it->weight < max) {
  56. it->rank = groupNum + 1;
  57. } else {
  58. playList.emplace_back(it);
  59. }
  60. }
  61. }
  62. }
  63. // 冠军
  64. playList.front()->rank = 1;
  65. cout << mices[0].rank;
  66. for (int i = 1; i < N; ++i) {
  67. cout << " " << mices[i].rank;
  68. }
  69. cout << "\n";
  70. }