解法一:数学
根据数学性质算出 n1
, n2
, n3
的大小,然后按格式输出。
#include <bits/stdc++.h>
using namespace std;
int main() {
int N, n1, n2, n3;
string str;
cin >> str;
N = str.length();
switch (N % 3) {
case 0:
n1 = n3 = N / 3;
n2 = N / 3 + 2;
break;
case 1:
n1 = n2 = n3 = (N + 2) / 3;
break;
case 2:
n1 = n3 = (N + 1) / 3;
n2 = n1 + 1;
}
int head = 0, tail = N - 1;
for (int i = 0; i < n1 - 1; ++i, ++head, --tail) {
cout << str[head];
for (int j = 0; j < n2 - 2; ++j) {
cout << " ";
}
cout << str[tail] << '\n';
}
for (int i = head; i <= tail; ++i) {
cout << str[i];
}
cout << '\n';
}