题目链接:https://www.patest.cn/contests/pat-a-practise/1056
采用递归调用的方法求解
#include <cstdio>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
#include <map>
#include <numeric>
using namespace std;
struct Mice{
int id;
int wt;
int rk;
int _rank;
Mice(){}
};
bool cmp1(const Mice &a ,const Mice &b){return a.rk>b.rk;}
bool cmp2(const Mice &a ,const Mice &b){return a.id<b.id;}
vector<Mice> mices;
int total, groupNum;
void proc(vector<int> _orders , int _rk){
for(int i=0;i<_orders.size();i++)mices[ _orders[i] ].rk=_rk;
vector<int> next;
for(int i=0;i<_orders.size();i+=groupNum){
int t=(i+groupNum)<_orders.size() ? groupNum : ( _orders.size()-i ) ;
int maxID=-1 , maxWt=-1;
for(int j=i; j<i+t; j++){
if(mices[_orders[j]].wt > maxWt){
maxWt=mices[_orders[j]].wt ;
maxID=_orders[j];
}
}
next.push_back(maxID);
}
if(next.size()==1)mices[next.front()].rk=_rk+1;
else proc(next,_rk+1 );
return;
}
int main(){
cin>>total>>groupNum;
mices.resize(total);
vector<int> orders(total);
for(int i=0;i<total;i++){
mices[i].id=i;
cin>>mices[i].wt;
}
for(int i=0;i<total;i++)cin>>orders[i];
proc(orders , 0);
sort(mices.begin() , mices.end() ,cmp1);
mices[0]._rank=1;
for(int i=1;i<mices.size();i++) {
if(mices[i].rk==mices[i-1].rk) mices[i]._rank=mices[i-1]._rank;
else mices[i]._rank=i+1;
}
sort(mices.begin() , mices.end() ,cmp2);
for(int i=0;i<mices.size();i++){
printf("%d", mices[i]._rank);
if(i<mices.size()-1)printf(" ");
}
return 0;
}