1109 Group Photo

1109 Group Photo ,第1张

#include 
using namespace std;

class people{
public:
    string name;
    int height;
};

bool cmp(people a,people b){   //定义comparator
    if(a.height==b.height)
        return a.name<b.name;  //如果身高一样,按升序排列
    else
        return a.height>b.height;   //如果身高不一样,按降序排列
}



int main(){
    int n,k;   //k--rows    n--people
    cin>>n>>k;
    int front_row=n/k;    //前面每行人数
    int last_row=n-front_row*(k-1);   //最后一行人数
    vector<string>photo(k);   //最后输出的容器
    vector<people>a(n);
    for(int i=0;i<n;i++)       //读入数据
        cin>>a[i].name>>a[i].height;
    sort(a.begin(),a.end(),cmp);    //排序

//    for(int i=0;i
//        cout<

    int pos=0;     //pos--从n个人中一个一个读取
    for(int i=k-1;i>=0;i--){      //一行一行遍历,从最后一行开始
        string s="";
        if(i==k-1){      //最后一行
            s+=a[pos].name;     //先取一个人进来,然后在他的左边、右边插入
            pos++;
            int fangxiang=1;     //判断插入的方向,是左边还是右边  1-左边  0-右边
            for(int j=1;j<last_row;j++){
                if(fangxiang){        //左边插入--字符串头部插入
                    s.insert(0," ");
                    s.insert(0,a[pos].name);
                    fangxiang=0;
                    pos++;
                }
                 else{       //右边插入--字符串尾部插入
                    s.push_back(' ');
                    s+=a[pos].name;
                    fangxiang=1;
                    pos++;
                }
            }
        }
        else{     //前面几行
            s+=a[pos].name;
            pos++;
            int fangxiang=1;     //插入方式和上面一样
            for(int j=1;j<front_row;j++){
                if(fangxiang){
                    s.insert(0," ");
                    s.insert(0,a[pos].name);
                    fangxiang=0;
                    pos++;
                }
                else{
                    s.push_back(' ');
                    s+=a[pos].name;
                    fangxiang=1;
                    pos++;
                }
            }
        }
        photo[i]=s;     //将每一行按字符串存起来
    }

    for(int i=photo.size()-1;i>0;i--)      //输出
        cout<<photo[i]<<endl;
    cout<<photo[0];

}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/634958.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-16
下一篇2022-04-16

发表评论

登录后才能评论

评论列表(0条)

    保存