1056. Mice and Rice (25)
贴一个模拟题,不知道为什么这题调了很久很久。
题目意思是给出节点数,参加每场比赛的最大节点数,之后顺序给出节点权值和节点出场顺序,顺序输出节点排名;每场比赛有只有一个节点晋级,其余节点排名并列。
一开始想法很简单,因为题目中乱序给出权值,就想直接用线性表(数组)存数据,用简单的循环语句执行,后来发现不是很容易写循环,遂想其他的数据结构减小难度,于是用最常见的队列来存。
将队列看成是比赛榜单,在榜单上意味着还在比赛,否则淘汰。首先全部序号入队,依次.pop( )从队头取序号每Ng个序号判断一次,抽出其中的获胜者序号重新放入队尾,其他的算淘汰,这时要同步记录比赛层次,每层淘汰的人数。由于提前计算了比赛的层数,可以直接用while( )循环控制结束。
之所以调试很久是在于思路不清,思路不清,思路不清!很多细节都是出错了才开始想,而不是一开始就想明白。
经此可知这种小题目如果不认真对待也可能卡人。
下面贴代码。
*注意
代码中的 rank 变量实际代表节点所在层数,这鬼代码真是一坨……
#include<iostream>
#include<cstring>
#include<math.h>
#include<queue>
using namespace std;
const int maxn=1005;
int main()
{
int Np,Ng,weight[maxn],ranklist[maxn],cano[maxn],rank,layer[maxn];
queue<int> Q;
int counter,temp,point,Nptemp,popcounter;
while(cin>>Np>>Ng)
{
//输入
for(int i=0;i<Np;i++)
cin>>weight[i];
for(int i=0;i<Np;i++)
cin>>cano[i];
//求最高rank
temp=Np;
for(rank=1;temp>1;rank++)
{
temp=ceil((float)temp/(float)Ng);
}
//队列操作
for(int i=0;i<Np;i++)
Q.push(cano[i]);
Nptemp=Np;
while(rank>=1)
{
layer[rank]=0;
for(int i=1;i<=Nptemp;)
{
counter=1; temp=-1;
while(counter<=Ng && i<=Nptemp)
{
i++;
counter++;
ranklist[Q.front()]=rank;
if(temp<weight[Q.front()])
{
temp=weight[Q.front()];
point=Q.front();
Q.pop();
layer[rank]++;
}
else
{
Q.pop();
layer[rank]++;
}
}
Q.push(point);
layer[rank]--;
}
rank--;
Nptemp=ceil((float)Nptemp/(float)Ng);
}
//输出
layer[1]=1;
for(int i=0;i<Np;i++)
{
temp=ranklist[i];
for(int j=1;j<temp;j++)
ranklist[i]+=layer[j];
ranklist[i]-=temp;
ranklist[i]++;
}
for(int i=0;i<Np-1;i++)
cout<<ranklist[i]<<" ";
cout<<ranklist[Np-1]<<endl;
}
}
另附打钩图: