PAT 1055.集体照

看的网上的思路


首先结构体的sort排序

int cmp(struct People a,struct People b)
{
	return a.height != b.height ? a.height> b.height : a.name < b.name;
}

按身高从高到低排,按名字从小到大排


sort实现原理

原始的cmp是

return a<b;
当a<b时返回真,按从小到大排。

可以自己修改cmp,真的返回什么就怎么排序


这题用了vector容器

vector使用方法

vector<something> p(n);
something换成自己需要的类型


思路:

一排一排的

最后一排站了多的人,计算最后一排的人数

int row = k;
if(row == k)
{
	m = n - n/k*(k-1);
}
row--;

当row!=k时

else
{
	m = n/k;
}


后面站位先找到中心点

vector<string> stemp(m);
stemp[m/2] = p[t].name;

然后从中往左边排,要左右顺序排,所以中间隔两个

int j = m/2-1;
for(i = t+1;i<t+m;i=i+2)
{
	stemp[j--] = p[i].name;
}


然后从中往右排

j = m/2+1;
for(i=t+2;i<t+m;i=i+2)
{
	stemp[j++] = p[i].name;
} 

最后打印啦



完整code:

#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;

struct People
{
	string name;
	int height;
};

int cmp(struct People a,struct People b)
{
	return a.height != b.height ? a.height> b.height : a.name < b.name;
}

int main()
{
	int n,i,k;
	cin >> n >> k;
		vector<People> p(n);
	for(i=0;i<n;i++)
	{
		cin >> p[i].name;
		cin >> p[i].height;
	}
	
	sort(p.begin(),p.end(),cmp);//从高到矮排 
	
//	cout << p[0].name;
	int t=0,row = k,m;
	while(row)
	{
		//cout << row << " ";
		if(row == k)
		{
			m = n - n/k*(k-1);
		}
		else
		{
			m = n/k;
		}
		//cout << m << endl;
	
		vector<string> stemp(m);
		stemp[m/2] = p[t].name;
		//左边
		int j = m/2-1;
		for(i = t+1;i<t+m;i=i+2)
		{
			stemp[j--] = p[i].name;
		}
		//右边
		j = m/2+1;
		for(i=t+2;i<t+m;i=i+2)
		{
			stemp[j++] = p[i].name;
		} 
		
		cout << stemp[0];
		for(i=1;i<m;i++)
		{
			cout << " " << stemp[i];
		}
		cout << endl;
		t = t+m;
		row--;
	}
	return 0;
} 


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值