算法习题---5.8Unix ls命令(Uva400)
一:题目
输入正整数n以及n个文件名,将这n个文件名按照ASCII优先升序排列,按列优先方式左对齐输出。
注意:文件名最长的为M,那么最右列字符串长度为M,其他列的长度为M+2
注意:一列最多允许出现60个字符
(一)样例输入
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
(二)样例输出
------------------------------------------------------------ 12345678.123 size-1 2short4me size2 mid_size_name size3 much_longer_name tiny shorter very_long_file_name ------------------------------------------------------------ Alfalfa Cotton Joe Porky Buckwheat Darla Mrs_Crabapple Stimey Butch Froggy P.D. Weaser ------------------------------------------------------------ Alice Chris Jan Marsha Ruben Bobby Cindy Jody Mike Shirley Buffy Danny Keith Mr._French Sissy Carol Greg Lori Peter
二:代码实现
#define _CRT_SECURE_NO_WARNINGS #include <iostream> #include <string> #include <algorithm> #define MAX 100 #define MAX_COL 60 using namespace std; void printStr(const string &str, int len, char ch) { cout << str; for (int i = str.length(); i < len; i++) cout << ch; } int main() { freopen("data5_8.in", "r", stdin); freopen("data5_8.out", "w", stdout); int num,max_len,rows,cols; string FileList[MAX]; while (cin >> num) { max_len = 0; for (int i = 0; i < num; i++) { cin >> FileList[i]; FileList[i].length() > max_len ? max_len = FileList[i].length() : max_len; } //计算行列 cols = (MAX_COL - max_len) / (2 + max_len) + 1; rows = (num - 1) / cols + 1; //数据处理,进行排序 sort(FileList, FileList + num); //进行数据输出 printStr("", 60, '-'); cout << endl; for (int r = 0; r < rows; r++) { for (int c = 0; c < cols; c++) printStr(FileList[rows*c + r], c == cols - 1 ? max_len : max_len + 2, ' '); cout << endl; } } freopen("CON", "r", stdin); freopen("CON", "w", stdout); return 0; }