题意:输入N个“文件名”(filename),要求将这些“文件名”按ASCII表排序后输出,输出的格式要求是:
1、先输出60个“-”字符后换行再输出这些“文件名”;
2、每个“文件名”的输出长度为其中最长“文件名”的长度(maxl)+2(长度不足时,就用空格补位);(我对这句话 “The rightmost column will be the width of the longest filename and all other columns will be the width of the longest filename plus 2.” 一直存有疑惑,因为只有当最右边的一列的“文件名”都以【maxl+2】的长度输出时才能AC,这与“The rightmost column will be the width of the longest filename”相悖)
3、一行最多能输出60个字符,输出时尽量要将这60个字符占满(即列数要最大化)(There will be as many columns as will fit in 60 characters.)。
思路:排序用qsort或sort解决(俺不怎么会用qsort),重点是计算行数(row)和列数(col)及输出。
列数:因为一行最多60个字符,除了最右边的一列长度为maxl,其它列的长度都为maxl+2,假设最右边的一列长度也为maxl+2,一行的总长度自然也+2,则col=(60+2)/(maxl+2)。
行数:自然会想到row=n/col,但 可以自行根据样例检验一下,当n%col不为0时,这样算row会少了1,所以row=n%col?n/col+1:n/col。
Code:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
struct Fn{
char fl[80];
};
Fn ls[110];
bool cmp(Fn a,Fn b){
return strcmp(a.fl,b.fl)<0;
}
int main()
{
int n;
while(~scanf("%d",&n)){
int maxl=0;
for(int i=0;i<n;i++){
scanf("%s",ls[i].fl);
int len=strlen(ls[i].fl);
if(len>maxl)
maxl=len;
}
sort(ls,ls+n,cmp);
for(int i=0;i<n;i++){
int len=strlen(ls[i].fl);
for(int j=len;j<maxl+2;j++)
ls[i].fl[j]=' ';
ls[i].fl[maxl+2]='\0';
}
int col=(60+2)/(maxl+2);
int row=n%col?n/col+1:n/col;
printf("------------------------------------------------------------\n");
for(int i=0;i<row;i++){
for(int j=i;j<n;j+=row)
printf("%s",ls[j].fl);
printf("\n");
}
}
return 0;
}
--------------------------------------------------------------------------------------------
Keep It Simple,Stupid!
--------------------------------------------------------------------------------------------

701

被折叠的 条评论
为什么被折叠?



