By Jalan
知识工具需求
数学
数据结构和算法
语言
题干
有个老鼠吃米的游戏,一开始我还以为是邮递员问题,后来发现只需要排个序就行…
输入条件
Np参赛人员和Ng每组的老鼠数量<=1000
末尾不够Ng的会被加到最后一组里
下面一行是第i个老鼠的体重,0-Np-1,
下面一行是比赛顺序0-Np-1
输出条件
输出排名.
例子
例1
输入
11 3
25 18 0 46 37 3 19 22 57 56 10
6 0 8 7 10 5 9 1 4 2 3
输出
5 5 5 2 5 5 5 3 1 3 5
题解
第一次
思路
- 输入体重到weight和比赛顺序order还有NpNg
- 编写函数match,找出本层的优胜者录入promote,把失败者写到一个tempLoser里加到loser二维数组里.
- 使用loser数组给rank进行排名
- 输出
预期时间复杂度
logn?
编写用时
55分钟
代码
CPP
#include <bits/stdc++.h>
#include <stdio.h>
#include <vector>
using namespace std;
int Np, Ng;
vector<int> weight;
vector<int> order;
void match(vector<int> &compete, vector<int> &promote, vector<vector<int>> &loser)
{
int fullGroup = compete.size() / Ng;
int lastGroupNumber = compete.size() % Ng;
vector<int> tempLoser;
int maxIndex;
if (fullGroup) //整组部分
{
for (int i = 0; i < fullGroup; i++)
{
maxIndex = i * Ng;
for (int j = 0; j < Ng; j++)
{
if (weight[compete[i * Ng + j]] > weight[compete[maxIndex]])
{
maxIndex = i * Ng + j;
}
}
promote.push_back(compete[maxIndex]);
for (int j = 0; j < Ng; j++)
{
if (i * Ng + j != maxIndex)
{
tempLoser.push_back(compete[i * Ng + j]);
}
}
}
}
//余下部分
if (lastGroupNumber)
{
maxIndex = compete.size() - 1;
for (int i = 0; i < lastGroupNumber; i++)
{
if (weight[compete[maxIndex]] < weight[compete[compete.size() - 1 - i]])
{
maxIndex = compete.size() - 1 - i;
}
}
promote.push_back(compete[maxIndex]);
for (int i = 0; i < lastGroupNumber; i++)
{
if (maxIndex != compete.size() - 1 - i)
{
tempLoser.push_back(compete[compete.size() - 1 - i]);
}
}
}
loser.push_back(tempLoser);
}
int main(int argc, char const *argv[])
{
//1
scanf("%d%d", &Np, &Ng);
weight.resize(Np);
order.resize(Np);
for (int i = 0; i < Np; i++)
{
scanf("%d", &weight[i]);
}
for (int i = 0; i < Np; i++)
{
scanf("%d", &order[i]);
}
//2
// for (int i = 0; i < Np; i++)
// {
// printf("%d ",weight[order[i]]);
// }
vector<int> promote;
vector<int> compete(order);
vector<vector<int>> loser;
while (compete.size() != 1)
{
match(compete, promote, loser);
compete = promote;
promote.clear();
}
//3
vector<int> rank(Np);
rank[compete[0]] = 1;
int r = 2;
for (int i = (int)loser.size() - 1; i >= 0; i--)
{
for (int j = 0; j < loser[i].size(); j++)
{
rank[loser[i][j]] = r;
}
r += loser[i].size();
}
//4
for (int i = 0; i < rank.size(); i++)
{
printf("%d", rank[i]);
if (i != (int)rank.size() - 1)
{
printf(" ");
}
}
return 0;
}
运行用时
结尾
看在我写了这么多注释的份上可以给我点个赞嘛,求求惹=]砰砰砰,给我加点写下去的油呀@.@
也欢迎关注我的CSDN账号呀,接下来两个月我应该会按这个格式更新所有的PTA甲级题目
**开心code每一天**