UVa400
非常不明白为什么UNIX上的ls命令会按照一列一列竖着的方式输出,反正这道题目很难写,主要有下面几个坑:
- 输出时候只能按照行输出,但是字典序是按照列排列的,数组索引需要仔细斟酌一下
- 文件名长度不足
M
要用空格补齐,即使是这一行最后的文件名,否则uDebug的例子过不去 - 其实是每一行第一列的文件名补齐为
M
,如果有下一列,再输出那个2
。这一点和书上的代码不一样,不知道书上的能不能AC,反正我的AC了
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int n = 0;
while (cin >> n){
cin.get();
vector<string> vecstr;
string strFile;
size_t M = 0;
for (int i = 0; i < n; i++)
{
cin >> strFile;
if (strFile.size() > M) M = strFile.size();
vecstr.push_back(strFile);
}
sort(vecstr.begin(), vecstr.end());
//col * M + (col - 1) * 2 <= 60
//col = 62 / (M + 2)
size_t col = 62 / (M + 2);
size_t row = vecstr.size() / col;
if (row * col < vecstr.size()) row++;
cout << "------------------------------------------------------------" << endl;
for (size_t i = 0; i < row; i++)
{
cout << vecstr[i] << string(M - vecstr[i].size(), ' ');
for (size_t j = 1; j < col; j++)
{
size_t idx = j * row + i;
if (idx < vecstr.size()){
cout << " " << vecstr[idx] << string(M - vecstr[idx].size(), ' ');
}
else break;
}
cout << endl;
}
}
return 0;
}
/*
10
tiny
2short4me
very_long_file_name
shorter
size-1
size2
size3
much_longer_name
12345678.123
mid_size_name
12
Weaser
Alfalfa
Stimey
Buckwheat
Porky
Joe
Darla
Cotton
Butch
Froggy
Mrs_Crabapple
P.D.
19
Mr._French
Jody
Buffy
Sissy
Keith
Danny
Lori
Chris
Shirley
Marsha
Jan
Cindy
Carol
Mike
Greg
Peter
Bobby
Alice
Ruben
*/