1031 Hello World for U (20 point(s)) - C語言 PAT 甲級

1031 Hello World for U (20 point(s))

Given any string of N (≥ 5) characters, you are asked to form the characters into the shape of U. For example, helloworld can be printed as:

h   !
e   d
l    l
lowor

That is, the characters must be printed in the original order, starting top-down from the left vertical line with n1 characters, then left to right along the bottom line with n2 characters, and finally bottom-up along the vertical line with n3 characters. And more, we would like U to be as squared as possible – that is, it must be satisfied that n1 = n3 = max { k | k ≤ n2 for all 3 ≤ n2 ≤ N } with n1 + n2 + n3 − 2 = N.

Input Specification:

Each input file contains one test case. Each case contains one string with no less than 5 and no more than 80 characters in a line. The string contains no white space.

Output Specification:

For each test case, print the input string in the shape of U as specified in the description.

Sample Input:

helloworld!

Sample Output:

h   !
e   d
l    l
lowor

題目大意:

輸入的字符串,按照 U 字型輸出;

n1 和 n3 表示兩條豎線上字符的總個數,n2 表示底部橫線上字符的總個數,並要求:

  1. n1 == n3
  2. n2 >= n1
  3. n1 取儘可能大的值
設計思路:

難點在於確定 n1、n2 的值;

因爲 U 分爲 n1、n2、n3 三條邊,且重疊了兩個字符,所以設:

  • n = 原字符串長度 + 2 = n1 * 2 + n2
    • 若 n % 3 == 0,則 n1 == n2 == n3
    • 若 n % 3 > 0,並且需要 n2 >= n1,那麼把多出的餘數給 n2 就行了;
  • 所以 n1 = n / 3,n2 = n / 3 + n % 3;

確定了三條邊的長度,利用一個頭指針和一個尾指針,按行輸出原字符串即可

編譯器:C (gcc)
#include <stdio.h>
#include <string.h>

int main(void)
{
        char str[81], *p, *q;
        int n1, n2, count;
        int i, j;

        scanf("%s", str);

        count = strlen(str) + 2;
        p = str;
        q = str + (count - 2 - 1);
        n1 = count / 3;
        n2 = count / 3 + count % 3;
        for (i = 0; i < n1 - 1; i++) {
                printf("%c", *p);
                p++;
                for (j = 1; j < n2 - 1; j++)
                        printf(" ");
                printf("%c\n", *q);
                q--;
        }
        for (p; p <= q; p++)
                printf("%c", *p);

        return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章