1. 程式人生 > 其它 >《演算法筆記》3.3小節——入門模擬->圖形輸出 問題 B: Hello World for U

《演算法筆記》3.3小節——入門模擬->圖形輸出 問題 B: Hello World for U

技術標籤:演算法字串

題目描述

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:

在這裡插入圖片描述

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.

輸入

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.

輸出

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

樣例輸入 Copy

helloworld!

樣例輸出 Copy

在這裡插入圖片描述

提示

這一題需要解決的問題是將一個字串寫成U字形。拿到這一題的第一映像是U字的寫法(可沒有茴香豆的“茴”寫法多),先是寫第一排第一個字元,然後寫第二排第一個字元……然後是最後一排,然後是倒數第二排……但在C語言中如果我們要這樣寫U字形的字串就需要在陣列中操作了。如果是直接輸出的話,那隻能自上至下一行一行輸出。首先是第一行,寫出第一個字元和最後一個字元,第二行寫出第二個字元和倒數第二個字元……最後是最後一行。需要注意的是除了最後一行輸出所有字元,前面每一行只輸出兩個字元。中間還有空格來隔開每行的兩個字元(具體有多少空格,待會計算)。

思路有了,看看具體的要求。字串的長度是N,n1,n3代表兩邊每列字元的數目。n2代表最後一行的字元數。題目中給了一個算式:

n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N } with n1 + n2 + n3 - 2 = N.

仔細研究這個算式,這裡的k是不大於n2的,也就是說n1和n3是不大於n2且滿足n1+n2+n3=N+2的最大值。那麼自然有n1=n3=(N+2)/3,n2=N+2-(n1+n3)。也就是說設side為兩邊的字元數(包括最後一行的兩端),則side=n1=n3=(N+2)/3。設mid為最後一行除去兩端的兩個字元後剩下的字元數,mid=N-side*2(總長度減去兩邊的字元數)。同時mid也是我們輸出除最後一行外前面所有行需要空出的空格數。

最後如何在第一行輸出第一個字元和最後一個字元呢?那自然是str[0]和str[len-1-i](len為字串的長度,也就是N)。

於是問題完美解決,步驟如下:

1)計算字串長度len;

2)計算兩邊的字元數side=(len+2)/3;

3)計算最後一行中間的字元數(前面每行中間的空格數);

4)輸出每行相應的字元。

由於該題目不難,也沒有什麼需要特別注意的,我也就不寫注意點了。具體細節詳見參考程式碼。

程式碼

初出茅廬,請多指教!

#include<stdio.h>
#include<string.h>

int main(){
	char word[1000];
	scanf("%s",word);
	int N=strlen(word);
	int n1=(N+2)/3;
	int n3=n1;
	int n2=N+2-n1-n3;
	int i,j;
	for(i=0;i<n1-1;i++){
		printf("%c",word[i]);
		for(j=0;j<n2-2;j++){
			printf(" ");
		}
		printf("%c\n",word[N-1-i]);
	}
	for(i=n1-1;i<n1-1+n2;i++){
		printf("%c",word[i]);
	}
	printf("\n");
	return 0;
}