PAT 乙级 1055. 集体照 (25) C++版

拍集体照时队形很重要,这里对给定的N个人K排的队形设计排队规则如下:

  • 每排人数为N/K(向下取整),多出来的人全部站在最后一排;
  • 后排所有人的个子都不比前排任何人矮;
  • 每排中最高者站中间(中间位置为m/2+1,其中m为该排人数,除法向下取整);
  • 每排其他人以中间人为轴,按身高非增序,先右后左交替入队站在中间人的两侧(例如5人身高为190、188、186、175、170,则队形为175、188、190、186、170。这里假设你面对拍照者,所以你的左边是中间人的右边);
  • 若多人身高相同,则按名字的字典序升序排列。这里保证无重名。

现给定一组拍照人,请编写程序输出他们的队形。

输入格式:

每个输入包含1个测试用例。每个测试用例第1行给出两个正整数N(<=10000,总人数)和K(<=10,总排数)。随后N行,每行给出一个人的名字(不包含空格、长度不超过8个英文字母)和身高([30, 300]区间内的整数)。

输出格式:

输出拍照的队形。即K排人名,其间以空格分隔,行末不得有多余空格。注意:假设你面对拍照者,后排的人输出在上方,前排输出在下方。

输入样例:

10 3
Tom 188
Mike 170
Eva 168
Tim 160
Joe 190
Ann 168
Bob 175
Nick 186
Amy 160
John 159

输出样例:

Bob Tom Joe Nick
Ann Mike Eva
Tim Amy John

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <algorithm>

using namespace std;
struct People {
string name;
int high;
};

bool cmp(People p1, People p2) {
if (p1.high < p2.high) {
return true;
} else if (p1.high > p2.high) {
return false;
} else {
return p1.name > p2.name;
}
}

int main() {
int n = 0, k = 0;
cin >> n >> k;
struct People *peoples = new struct People[n];
for (int i = 0; i < n; i++) {
cin >> peoples[i].name >> peoples[i].high;
}

sort(peoples, peoples + n, cmp);

int per = n / k;
for (int i = k; i >= 1; i--) {
int len = 0;
int index = 0;
if (i == k) {
len = n - k * per + per;
index = n - 1;
} else {
len = per;
index = i * per - 1;
}

People *temp = new People[len];
int left = len / 2;
int right = len / 2;
temp[left] = peoples[index--];
left--;
right++;
while (left >= 0 && right < len) {
temp[left--] = peoples[index--];
temp[right++] = peoples[index--];
}

if (left >= 0) {
temp[left] = peoples[index];
} else if (right < len) {
temp[right] = peoples[index];
}

for (int j = 0; j < len - 1; j++) {
cout << temp[j].name << " ";
}
cout << temp[len - 1].name << endl;;
}

delete[] peoples;
return 0;
}