解法一:数学

根据数学性质算出 n1n2n3 的大小,然后按格式输出。

  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. int main() {
  4. int N, n1, n2, n3;
  5. string str;
  6. cin >> str;
  7. N = str.length();
  8. switch (N % 3) {
  9. case 0:
  10. n1 = n3 = N / 3;
  11. n2 = N / 3 + 2;
  12. break;
  13. case 1:
  14. n1 = n2 = n3 = (N + 2) / 3;
  15. break;
  16. case 2:
  17. n1 = n3 = (N + 1) / 3;
  18. n2 = n1 + 1;
  19. }
  20. int head = 0, tail = N - 1;
  21. for (int i = 0; i < n1 - 1; ++i, ++head, --tail) {
  22. cout << str[head];
  23. for (int j = 0; j < n2 - 2; ++j) {
  24. cout << " ";
  25. }
  26. cout << str[tail] << '\n';
  27. }
  28. for (int i = head; i <= tail; ++i) {
  29. cout << str[i];
  30. }
  31. cout << '\n';
  32. }