UVa 400 - Unix ls

Contents

  1. 1. Problem
  2. 2. Solution
  3. 3. Code

Problem

中文網址

注意字串的順序輸出時是由上到下:
1 4
2 5
3 6

Solution

分別計算每列可容納幾個和有幾列。
再依輸出位置去算要取哪個字串: file[i + r*j]

Code

UVa 400
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#define L 60
using namespace std;

int main()
{
int n;
vector<string> file;
string str;
while (scanf("%d", &n) != EOF)
{
int max_len = 0;
for (int i = 0; i < n; i++)
{
cin >> str;
file.push_back(str);
int len = str.length();
if (len > max_len)
max_len = len;
}

sort(file.begin(), file.end());
int x = 1 + (L - max_len) / (max_len + 2);//一列最多可容納幾個
int r = (int)n / x + (n%x ? 1 : 0);//有幾列

puts("------------------------------------------------------------");

for (int i = 0; i < r; i++)
{
for (int j = 0; j < x; j++)
{
if (i + r*j >= n)
break;

if (j)
putchar(' '), putchar(' ');

printf("%-*s", max_len, file[i + r*j].c_str());
}
putchar('\n');
}

file.clear();
}

return 0;
}