UVa 400 (水题) Unix ls

时间:2023-11-10 16:24:38

题意:

有n个文件名,排序后按列优先左对齐输出。设最长的文件名的长度为M,则最后一列长度为M,其他列长度为M+2.

分析:

这道题很简单,但要把代码写的精炼,还是要好好考虑一下的。lrj的代码中有两个亮点,一个是print子函数,一个就是行数的计算。用心体会

 #include <iostream>
#include <cstdio>
#include <string>
#include <algorithm>
using namespace std; const int maxl = ;
const int maxn = + ;
string names[maxn]; void print(const string& s, int len, char extra)
{
printf("%s", s.c_str());
for(int i = s.length(); i < len; ++i) putchar(extra);
} int main()
{
//freopen("in.txt", "r", stdin);
int n;
while(scanf("%d", &n) == )
{
int M = ;
for(int i = ; i < n; ++i)
{
cin >> names[i];
M = max(M, (int)names[i].length());
}
sort(names, names + n);
int cols = (maxl - M) / (M + ) + , rows = (n - ) / cols + ;
print("", , '-');
puts("");
for(int r = ; r < rows; ++r)
{
for(int c = ; c < cols; ++c)
{
int index = c * rows + r;
if(index < n) print(names[index], c == cols- ? M : M+, ' ');
}
puts("");
}
} return ;
}

代码君