题目链接:PTA A1056 Mice and Rice
由此得到算法的大致轮廓:
1、没读懂题,样例都没看懂
2、善用结构体
3、Segmentation Fault:所谓的段错误就是指访问的内存超过了系统所给这个程序的内存空间,段错误应该就是访问了不可访问的内存,这个内存要么是不存在的,要么是受系统保护的。
第一次遇到这种错误,看了大神的,发现最后一组老鼠数不足ng时,越界了。。。
#include<iostream>
#include<algorithm>
#include<string>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<queue>
using namespace std;
const int maxn = 1010;
struct mouse
{
int w; //weight
int r; //rank
}mouse[maxn];
int main()
{
int np,ng;
scanf("%d%d",&np,&ng);
for(int i=0;i<np;i++)
scanf("%d",&mouse[i].w);
queue<int> q;
int order;
for(int i=0;i<np;i++)
{
scanf("%d",&order);
q.push(order);
}
int tmp = np, group; //tmp为当前轮的比赛总老鼠数
while(q.size()!=1) //控制轮数
{
if(tmp%ng==0) group = tmp/ng; //得到每一轮的分组数
else group = tmp/ng+1;
for(int i=0;i<group;i++) //枚举当前轮的每一组
{
int max = q.front(); //max存放该组质量最大的编号,先初始化为队首元素
for(int j=0;j<ng;j++) //枚举当前组的每一只
{
if(i*ng+j>=tmp) //最后一组老鼠数不足ng时起作用,退出循环
break;
int front = q.front(); //front和后面的pop一起控制元素后移
if(mouse[front].w > mouse[max].w)
max = front;
mouse[front].r = group+1; //该轮老鼠排名都为group+1,晋级的后面会被覆盖掉
q.pop();
}
q.push(max); //该组最大的老鼠晋级
}
tmp = group; //得到下一轮的总老鼠数
}
mouse[q.front()].r = 1; //当队列只剩一只老鼠时,令其排名为1
for(int i=0;i<np;i++)
{
printf("%d",mouse[i].r);
if(i<np-1) printf(" ");
}
return 0;
}