UVA 400 Unix ls
阿新 • • 發佈:2019-02-10
nbsp length mes ace img 輸出字符串 圖片 class 計算列
題意:把輸入的字符串排序後,豎著按順序輸出(按列)。
思路:
①計算最大的M、行數、列數,然後逐行逐列輸出。
②行數的計算:
③列數的計算:
求得了行數列數也就得到了,註意利用技巧:rows = (n - 1) / cols + 1
④輸出的順序:
/*
舉例,有三行時下標如下:
0 3 6 9 ->c
1 4 7
2 5 6
↓
r
可推算出
輸出的下標為idx = c*rows + r;
*/
1 #include<iostream> 2 #include<algorithm> 3 #include<string> 4 using namespace std; 5 const int maxcol = 60; 6 const int maxn = 100 + 5; 7 string filename[maxn]; 8 //輸出字符串s,長度不足len時,補字符extra 9 void print(const string&s, int len, char extra) 10 { 11 cout << s;12 for (int i = s.length(); i < len; i++)//或者i=0;i<len-s.length() 13 { 14 cout << extra; 15 } 16 } 17 int main() 18 { 19 int n; 20 while (cin >> n) 21 { 22 int M=0;//M是最長的長度 23 for (int i = 0; i < n; i++) 24 { 25 cin >> filename[i];26 M = max(M, (int)filename[i].length()); 27 } 28 //計算列數cols和行數rows 29 int cols = (maxcol + 2) / (M + 2); 30 int rows = (n - 1) / cols + 1;//技巧 31 sort(filename, filename + n); 32 print("", 60, ‘-‘); 33 cout << "\n"; 34 for (int r = 0; r < rows; r++)//最外層是行 35 { 36 for (int c = 0; c < cols; c++)//列 37 { 38 //輸出 39 int idx = c*rows + r; 40 /* 41 舉例: 42 0 3 6 9 ->c 43 1 4 7 44 2 5 6 45 ↓ 46 r 47 可推算出 48 */ 49 if(idx<n) 50 print(filename[idx], c == cols-1 ? M : M + 2, ‘ ‘);//三目運算符 51 } 52 cout << "\n"; 53 } 54 } 55 return 0; 56 }
UVA 400 Unix ls