题
例题5-8 Unix is 命令(Unix is,UVA 400)。完整题目见参考[1]
#include <iostream> #include <string> #include <algorithm> using namespace std; const int maxcol = 60; const int maxn = 100 + 5; string filenames[maxn]; // 输出字符串s ,长度不足 len时补字符 extra void print(const string &s, int len, char extra) { cout << s; for (int i = 0; i != len - s.length(); ++i) { cout << extra; } } int main() { int n; while (cin >> n) { int M = 0; // 最长文件最开始是不知道的,要自己去求 for (int i = 0; i != n; ++i) { cin >> filenames[i]; M = max(M, (int)filenames[i].length()); // STL的max函数 // 强制转型是必要的,否则会有如下的错误 // [Error] no matching function for call to 'max(int&, std::basic_string<char>::size_type)' } // 计算列数 cols 和行数 rows // 附加条件每行最多输出60个字符,在此条件下要求行最少。 int cols = (maxcol - M) / (M + 2) + 1, rows = (n - 1) / cols + 1; // 最右列 有 M 个 字符 ,其它列都是 M + 2 个字符 // 确定了 列数,那么行数也唯一确定了 // PS. 这里 n 之所以 -1主要是服务于 刚好整除的情况, 不减1 的话 // 应用这个算式就会多一行。 print("", 60, '-'); cout << endl; sort(filenames, filenames + n); for (int r = 0; r != rows; ++r) { for (int c = 0; c != cols; ++c) { int idx = c * rows + r; // 计算应该填入当前坐标的 filename 的id if (idx != n) print(filenames[idx], c == cols - 1 ? M : M + 2, ' '); } cout << " "; } } return 0; }