题目:给你一些单词,排序后输出。从左到右,从上到下,递增。
分析:模拟,格式控制。
设单词中最长的长为L,摆满时每行有k个单词,前k-1个占L+2空间左对齐,最后一个占L空间。
没有字符的被占的空间均为空格。看下图就明白了('竖线是对应换行的位置):
注意:输出格式。
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <cstdio>
using namespace std;
char words[104][65];
int cmp( const void *p, const void *q )
{
char *a = (char *)p;
char *b = (char *)q;
int i = 0;
for ( ; a[i] == b[i] ; ++ i )
if ( a[i] == '\0' )
return -1;
return a[i] - b[i];
}
int main()
{
int n;
while ( ~scanf("%d",&n) ) {
for ( int i = 0 ; i < n ; ++ i )
scanf("%s",words[i]);
qsort( words, n, sizeof(words[0]), cmp );
int max_l = 0;
for ( int i = 0 ; i < n ; ++ i )
if ( max_l < strlen(words[i])+2 )
max_l = strlen(words[i])+2;
for ( int i = 0 ; i < 60 ; ++ i )
printf("-");
printf("\n");
int colu = 62/max_l;
int rows = (n-1)/colu+1;
for ( int i = 0 ; i < rows ; ++ i ) {
for ( int j = 0 ; j < colu ; ++ j ) {
printf("%s",words[j*rows+i]);
for ( int k = strlen(words[j*rows+i])+2 ; k < max_l ; ++ k )
printf(" ");
if ( j < colu-1 ) printf(" ");
if ( (j+1)*rows+i >= n ) break;
}
printf("|\n");
}
}
return 0;
}