您的位置:首页 > 其它

PAT (Advanced) 1056. Mice and Rice (25)

2018-03-06 14:48 429 查看
原题:1056. Mice and Rice (25)

解题思路:
题目对第三行数据的描述略坑。第三行的数实际上本身就是出场次序,不如第一个数为6,就代表6号老鼠第一个出场。
实际上就是循环找出每组最大的,直到只剩下一个老鼠。需要设计几个比较函数进行排序。

代码如下:#include<cstdio>
#include<algorithm>
#include<vector>
using namespace std;
const int maxn = 1000 + 5;

struct Mouse
{
int id;
int order;
int weight;
int round;
int Rank;
} mouse[maxn];

bool cmp1(Mouse a, Mouse b)
{
if(a.round != b.round) return a.round < b.round;
return a.order < b.order;
}

bool cmp2(Mouse a, Mouse b)
{
if(a.round != b.round) return a.round > b.round;
return a.order < b.order;
}

bool cmp3(Mouse a, Mouse b)
{
return a.id < b.id;
}
int main()
{
int ng, np;
while(scanf("%d%d", &np, &ng) == 2)
{
for(int i = 0; i < np; i++)
{
scanf("%d", &mouse[i].weight);
mouse[i].id = i;
mouse[i].round = 0;
}
for(int i = 0; i < np; i++)
{
int order;
scanf("%d", &order);
mouse[order].order = i;
}
int rnd = 1;
for(;;)
{
sort(mouse, mouse+np, cmp1);
int cnt = 0;
for(int i = 0; i < np && mouse[i].round == 0;)
{
int maxi = -1, maxw = -1;
for(int j = i; j < i+ng && j < np && mouse[j].round == 0; j++)
if(mouse[j].weight > maxw)
{
maxi = j;
maxw = mouse[j].weight;
}
for(int j = i; j < i+ng && j < np && mouse[j].round == 0; j++)
if(j != maxi) {mouse[j].round = rnd;cnt++;}

i += ng;
}
rnd++;
if(cnt == 0) //只剩一只了
{
mouse[0].round = rnd;
break;
}
}
//决定名次
sort(mouse, mouse+np, cmp2);
mouse[0].Rank = 1;
for(int i = 1; i < np; i++)
if(mouse[i].round == mouse[i-1].round) mouse[i].Rank = mouse[i-1].Rank;
else mouse[i].Rank = i + 1;
//输出
sort(mouse, mouse+np, cmp3);
printf("%d", mouse[0].Rank);
for(int i = 1; i < np; i++)
printf(" %d", mouse[i].Rank);
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: