【题目来源】
https://www.acwing.com/problem/content/1544/
【题目描述】
老鼠和大米是一个编程竞赛的主题,程序员们需要编写代码控制老鼠在给定的地图上移动,每只老鼠的目标都是吃掉尽可能多的大米,从而变成肥老鼠。
共有 NP 个程序员参赛,入场顺序随机,每 NG 个程序员被分为一组。
组中最胖的老鼠获胜,并进入下一轮。
所有在本回合中失败的老鼠排名都相同。
获胜者继续每 NG 个一组,进行比赛,直到决出唯一胜者为止。
为了简单起见,当程序员们提交了代码后,他们的老鼠的最终重量就已经确定了。
给定所有老鼠的重量和程序员们的参赛顺序,请你为程序员们排名。
【输入格式】
第一行包含两个整数 NP 和 NG,分别表示总参赛人数以及每组最多人数。
如果分组到最后,剩下不足 NG 个人,则剩下的所有人分为一组。
所有 NP 只老鼠的编号为 0∼NP−1。
第二行包含 NP 个不同的非负整数 Wi(i=0,1,…,NP−1),其中 Wi 表示编号为 i 的老鼠的重量。
第三行包含一个 0∼NP−1 的排列,表示老鼠的具体参赛顺序,以样例为例,6 号老鼠排在第一个,0 号老鼠排在第二个,以此类推。
【输出格式】
输出一行 NP 个整数,其中第 i 个整数表示编号为 i 的老鼠的最终排名。
【数据范围】
1≤NP≤1000,
2≤NG≤1000,
0≤Wi≤1000。
【输入样例】
11 3
25 18 0 46 37 3 19 22 57 56 10
6 0 8 7 10 5 9 1 4 2 3
【输出样例】
5 5 5 2 5 5 5 3 1 3 5
【算法分析】
● BFS算法助记:建-入-量:头-出:https://blog.csdn.net/hnjzsyjyj/article/details/125801217
● DFS算法模板:https://blog.csdn.net/hnjzsyjyj/article/details/118736059
【算法代码】
#include<bits/stdc++.h>
using namespace std;
const int N=1010;
struct Mouse {
int w;
int rank;
} a[N];
int main() {
int NP,NG,x; //NG:Number of mice in each group
cin>>NP>>NG;
for(int i=0; i<NP; i++) {
cin>>x;
a[i].w=x;
}
int index,group;
queue<int> q;
for(int i=0; i<NP; i++) {
cin>>index;
q.push(index);
}
int t=NP;
while(q.size()>1) {
if(t%NG==0) group=t/NG;
else group=t/NG+1;
for(int i=0; i<group; i++) {
int k=q.front();
for(int j=1; j<=NG; j++) { //NG:Number of mice in each group
if(i*NG+j>t) break;
if(a[q.front()].w>a[k].w) k=q.front();
a[q.front()].rank=group+1;
q.pop();
}
q.push(k);
}
t=group;
}
a[q.front()].rank=1;
for(int i=0; i<NP; i++) {
if(i==0) cout<<a[i].rank;
else cout<<" "<<a[i].rank;
}
return 0;
}
/*
in:
11 3
25 18 0 46 37 3 19 22 57 56 10
6 0 8 7 10 5 9 1 4 2 3
out:
5 5 5 2 5 5 5 3 1 3 5
*/
【参考文献】
https://www.acwing.com/solution/content/67706/
https://www.acwing.com/solution/content/153213/