2016-07-19
UVA - 400 Unix ls
题目大意:将输入的文件名按 ascll 码顺序输出。输出从上到下,从左到右,每一行不能超过 60 个字符,除了最后一列外,每列的格式控制长度为最长的文件名的长度 +2。
解题思路:先排序,然后一行一行输出,每行通过(j = i; j < N;j += b)输出。
注意:空格的个数要注意。
#include <iostream>
#include <cstring>
#include <stdlib.h>
#include <cstdio>
using namespace std;
char str[1000][100];
int Max;
int a;//一行有几个
int b;//一列有几个
int comp(const void *a , const void *b) {
return strcmp( (char*)a , (char*)b );
}
int main() {
int N;
while ( scanf("%d",&N) != EOF ) {
memset( str , '\0' , sizeof(str) );
scanf( "%s", str[0]);
Max = strlen(str[0]);
for (int i = 1; i < N; i++) {
scanf( "%s",str[i]);
if ( strlen( str[i] ) > Max )
Max = strlen( str[i] );
}
a = 62 / (Max + 2);
b = N/a;
if ( N % a ) b++;
qsort( str , N , sizeof(str[0]) , comp );
for (int i = 0; i < 60; i++)
cout << "-";
cout << endl;
for (int i = 0; i < b; i++) {
int t = 0;
for (int j = i; j < N; j += b) {
printf( "%s",str[j]);
t++;
for (int k = strlen( str[j] ); k < Max; k++)
printf(" ");
if ( t != a )
printf(" ");
}
printf("\n");
}
}
return 0;
}