解法一:队列
将老鼠加入队列,从队列头取出分组比较,将胜者加入队列尾,直到决出冠军。
败者 rank = 本轮分组数+1
。
#include <bits/stdc++.h>
using namespace std;
class Mice {
public:
int weight;
int rank;
};
int main() {
int N, M;
cin >> N >> M;
Mice mices[N];
for (int i = 0; i < N; ++i) {
cin >> mices[i].weight;
}
deque<Mice *> playList;
for (int i = 0, tmp; i < N; ++i) {
cin >> tmp;
playList.emplace_back(&mices[tmp]);
}
while (playList.size() > 1) {
int size = playList.size();
int groupNum = size / M + (size % M > 0);
vector<Mice *> matchList;
for (int i = 0; i < size; ++i) {
if (matchList.size() < M) {
matchList.emplace_back(playList.front());
playList.pop_front();
}
if (matchList.size() == M) {
int max = -1;
for (auto &it:matchList) {
if (it->weight > max) {
max = it->weight;
}
}
for (auto &it:matchList) {
if (it->weight < max) {
it->rank = groupNum + 1;
} else {
playList.emplace_back(it);
}
}
matchList.clear();
}
}
// 最后一组
if (!matchList.empty()) {
int max = -1;
for (auto &it:matchList) {
if (it->weight > max) {
max = it->weight;
}
}
for (auto &it:matchList) {
if (it->weight < max) {
it->rank = groupNum + 1;
} else {
playList.emplace_back(it);
}
}
}
}
// 冠军
playList.front()->rank = 1;
cout << mices[0].rank;
for (int i = 1; i < N; ++i) {
cout << " " << mices[i].rank;
}
cout << "\n";
}