A1056. Mice and Rice (25)
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
struct mouse {
int weight;
int rank;
};
int main(){
int NP, NG, i, j;
scanf("%d %d", &NP, &NG); // NP: mouse总数; NG: 每组mouse数
struct mouse mouse[NP];
for(i = 0; i < NP; i++){
scanf("%d", &mouse[i].weight);
}
queue<int> q;
int order;
for(i = 0; i < NP; i++){
scanf("%d", &order);
q.push(order);
}
int np = NP, ng = NG;
while(q.size() != 1){
int gnum = (np % ng == 0) ? (np / ng) : (np / ng + 1);
// 遍历每组
for(i = 0; i < gnum; i++){
int win= q.front();
// 遍历第i组
for(j = 0; j < ng; j++){
// 防止超出
if(i * ng + j >= np)
break;
int front = q.front();
if(mouse[front].weight > mouse[win].weight){
win = front;
}
mouse[front].rank = gnum + 1;
q.pop();
}
q.push(win);
}
np = gnum;
}
mouse[q.front()].rank = 1;
for(i = 0; i < NP; i++){
printf("%d", mouse[i].rank);
if(i < NP - 1)
printf(" ");
}
return 0;
}
本题也可以不用队列,只用简单数组实现,毕竟逻辑不复杂
#include <cstdio>
#include <cstring>
#include <algorithm>
//#include <queue>
using namespace std;
struct mouse {
int weight;
int rank;
};
int main(){
int NP, NG, i, j;
scanf("%d %d", &NP, &NG); // NP: mouse总数; NG: 每组mouse数
struct mouse mouse[NP];
int order[NP], nextorder[NP];
for(i = 0; i < NP; i++){
scanf("%d", &mouse[i].weight);
}
for(i = 0; i < NP; i++){
scanf("%d", &order[i]);
}
int np = NP, ng = NG;
while(np != 1){
int gnum = (np % ng == 0) ? (np / ng) : (np / ng + 1);
// 遍历每组
for(i = 0; i < gnum; i++){
int win= order[0];
// 遍历第i组
for(j = 0; j < ng; j++){
// 防止超出
if(i * ng + j >= np)
break;
int ckey = order[i * ng + j];
if(mouse[ckey].weight > mouse[win].weight){
win = ckey;
}
mouse[ckey].rank = gnum + 1;
}
nextorder[i] = win;
}
np = gnum;
for(i = 0; i < np; i++){
order[i] = nextorder[i];
}
}
mouse[order[0]].rank = 1;
for(i = 0; i < NP; i++){
printf("%d", mouse[i].rank);
if(i < NP - 1)
printf(" ");
}
return 0;
}