题目链接:
https://pintia.cn/problem-sets/994805260223102976/problems/994805272021680128
AC代码:https://blog.csdn.net/yjIvan/article/details/78594885
注意:
1、排序问题,先按照身高降序,后按名字升序
2、左右排列问题,偶数应该是:4、2、1、3;奇数应该为:4、2、1、3、5
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
struct person {
string name;
int height;
};
bool cmp(person A, person B) {
if (A.height != B.height)
return A.height > B.height;
else
return A.name < B.name;
}
int main() {
int N, K, rowNumber, remaider, row, index;
vector<person> team, singleRow;
person single;
cin >> N >> K;
rowNumber = N / K;
remaider = N % K;
for (int i = 0; i < N; i++) {
cin >> single.name >> single.height;
team.push_back(single);
}
sort(team.begin(), team.end(), cmp);
row = rowNumber + remaider;//第一行:为原本的rowNumber元素加上多余的元素
index = 0;
//1,输出最后一行(存在多余的人)
//2,输出其余的行
while (index < N) {
if (row % 2==0) {//行数为偶数
for (int i = row; i > 0; i -= 2) {
//从后往前,先把偶数入队
singleRow.push_back(team[index + i - 1]);
}
for (int i = 1; i < row; i += 2) {
//从前往后,把奇数入队
singleRow.push_back(team[index + i - 1]);
}
}
else {
//先把偶数入队
for (int i = row - 1; i > 0; i -= 2) {
singleRow.push_back(team[index + i - 1]);
}
//再把奇数入队,因为i从1开始,所以row所指的位为:奇数
for (int i = 1; i <= row; i += 2) {
singleRow.push_back(team[index + i - 1]);
}
}
//打印每一行
for (int j = 0; j < row; j++) {
if (j == 0) {
cout << singleRow[index + j].name;
}
else {
cout << " " << singleRow[index + j].name;
}
}
cout << endl;
index += row;//保证输出的行数
row = rowNumber;//每行应该有多少人
}
return 0;
}