https://pintia.cn/problem-sets/994805260223102976/problems/994805272021680128
这题搞死我啦,做了一下午。 一开始用了一个的方法,但是后面才意识到身高有相同的,所以放弃那个方法了。后面去学了用sort对二维数组进行排序,其中忘记把string转int来比较。排好序后开始排集体照的位置。用一个for循环代表访问队形的每一行,算出该行的总人数,找到最中点,找到应该站该行的人们,放到相应的位置上去。
#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(string a[], string b[]){
int ah = atoi(a[0].c_str()), bh = atoi(b[0].c_str());
if(ah == bh)// 如果身高相同
return a[1] > b[1];// 按照名字升序排序
else
return ah <= bh;// 按照身高升序排序
}
int main() {
int n, k, c, p, q, col, j, l, r, flag;
cin >> n >> k;
c = n/k;
string temp1, temp2, name[n], height[n], final[k][c*2];
// 动态创建二维数组
string **info = new string*[n];
for(int i=0; i<n; i++){
cin >> temp1 >> temp2;
info[i] = new string[2];
info[i][0] = temp2;
info[i][1] = temp1;
}
// 排序
sort(info, info+n, cmp);
// 对于每一行
for(int i=k-1; i>=0; i--){
// 算出当前行的人数
if(i==0){
col = c + n%k;
}else{
col = c;
}
flag = 0;
j = col/2;// 最中间的位置
l = col/2;
r = col/2;
// 找到站该行的人们
if(i==k-1){
p = 0;
}else{
p = q+1;
}
q = p+col-1;
// 放入对应位置
for(int t=q; t>=p; t--, flag++){
final[i][j]=info[t][1];
if(flag%2== 0){// 左边
l --;
j = l;
}else{// 右边
r ++;
j = r;
}
}
}
// 输出
for(int i=0; i<k; i++){
for(int j=0; j<c*2; j++){
if(final[i][j]!=""){
if(j>0)
cout << " ";
cout << final[i][j];
}
}
cout << endl;
}
return 0;
}