【PAT】A1056. Mice and Rice (25)

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值