#pragma warning(disable:4996)
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#include<algorithm>
#include<iostream>
#include<time.h>
#include<set>
#include<sstream>
#include<functional>
#include<cassert>
#include<list>
#include<iterator>
#include<utility>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include<ctype.h>
#include<map>
#include<stack>
#include<queue>
#include<cstdlib>
using namespace std;
string str[105];
const int INF = 0x3f3f3f3f;
int main()
{
ios::sync_with_stdio(false);
int n;
while (cin >> n)
{
int maxn = -INF;
for (int i = 1;i <=60;i++)
cout << "-";
cout << endl;
int flag = 0;
for (int i = 0;i < n;i++)
{
cin >> str[i];
int len = str[i].size();
if (len >60)
flag = 1;
if (len > maxn)
{
maxn = str[i].size();
}
}
if (!flag)
{
int numcolumn = 0;
for (int i = 1;i <= 60;i++)
{
if ((maxn + 2)*(i - 1) + maxn > 60)
{
numcolumn = i - 1;
break;
}
}
int numrow = 0;
for (int i = 1;i <= 60;i++)
{
if ((n - i*(numcolumn - 1)) <= i)
{
numrow = i;
break;
}
}
sort(str, str + n);
for (int i = 0;i < numrow*(numcolumn - 1);i++)
{
while (str[i].size() < (maxn + 2))
{
str[i] = str[i] + " ";
}
}
for (int i = numrow*(numcolumn - 1);i < n;i++)
{
while (str[i].size() < (maxn))
{
str[i] = str[i] + " ";
}
}
string temp[100];
for (int i = 0;i < 100;i++)
temp[i] = "";
for (int i = 1;i <= numrow;i++)
{
for (int j = 1;j <= numcolumn;j++)
{
if (((i - 1) + (j - 1) * numrow) >= n)
continue;
temp[i] = temp[i] + str[(i - 1) + (j - 1)*numrow];
}
}
for (int i = 1;i <= numrow;i++)
{
cout << temp[i] << endl;
}
}
else
{
for (int i = 0;i < n;i++)
cout << endl;
}
}
return 0;
}
刘汝佳的代码和我都是10ms
#pragma warning(disable:4996)
#include<cstdio>
#include<cstring>
#include<string>
#include<cmath>
#include<vector>
#include<algorithm>
#include<iostream>
#include<time.h>
#include<set>
#include<sstream>
#include<functional>
#include<cassert>
#include<list>
#include<iterator>
#include<utility>
#include <stdexcept>
#include <sstream>
#include <fstream>
#include<ctype.h>
#include<map>
#include<stack>
#include<queue>
#include<cstdlib>
using namespace std;
const int maxcol = 60;
const int maxn = 100 + 5;
string filenames[maxn];
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());
}
int cols = (maxcol - M) / (M + 2) + 1, rows = (n - 1) / cols + 1;
print("", 60, '-');
cout << "\n";
sort(filenames, filenames + n);
for (int r = 0;r < rows;r++)
{
for (int c = 0;c < cols;c++)
{
int idx = c*rows + r;
if (idx < n)
print(filenames[idx], c == cols - 1 ? M : M + 2, ' ');
}
cout << "\n";
}
}
return 0;
}