【题意+推导讲解】1031 Hello World for U (20 分)_15行代码AC
立志用最少的代碼做最高效的表達
PAT甲級最優題解——>傳送門
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 d
e l
l r
lowo
That is, the characters must be printed in the original order, starting top-down from the left vertical line with n?1??characters, then left to right along the bottom line with n?2?? characters, and finally bottom-up along the vertical line with n?3?? characters. And more, we would like U to be as squared as possible – that is, it must be satisfied that n?1??=n?3??=max { k | k≤n?2?? for all 3≤n?2??≤N } with n?1??+n?2??+n?3???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
題意:輸入一個字符串,按給定規則輸出。
規則:
1、按樣例中順序輸出字母
2、n1+n2+n3 = N+2
3、n2 >= 3
4、n1 <= n2
低級解法:定義雙重循環,i循環為n2,從3開始遍歷;j循環為n1,從i開始遍歷,等于0時停止 。 找到解后,按給定規律輸出。(解放雙手,暴力萬歲)
高級解法:手動推導,可得結論:n1=n3=(N+2)/3向下取整。n1,n2,n3確定以后按規定輸出。
低級解法
#include<bits/stdc++.h> using namespace std; int main() {ios::sync_with_stdio(false);string s; cin >> s;int len = s.length(), b, l_r;for(int i = 3; ; i++) //求n1和n2 for(int j = i; j >= 1; j--) if(j*2 + i == len+2) {b = i; l_r = j-1; goto loop;}loop:;//輸出 int k = 0; //計數器 for(int i = 0; i < l_r+1; i++) { //行數 for(int j = 0; j < b; j++) { //列數 if(i != l_r) if(j == 0) putchar(s[k]);else if(j == b-1) putchar(s[len- k++ -1]); else putchar(' ');else putchar(s[k++]); } putchar('\n'); }return 0; }高級解法
#include<bits/stdc++.h> using namespace std; int main(){string input; cin>> input//讀取字符串int n1=(input.size()+2)/3,n2=input.size()+2-2*n1;//獲取n1,n2//進行輸出for(int i=0;i<n1-1;++i){//前n1-1行,需要輸出首尾兩個字符,且每行字符數為n2printf("%c",input[i]);for(int j=0;j<n2-2;++j)printf(" ");printf("%c\n",input[input.size()-i-1]);}//最后一行將沒有輸出的n2個字符一次性輸出for(int i=0;i<n2;++i)printf("%c",input[n1-1+i]);return 0; }耗時:
總結
以上是生活随笔為你收集整理的【题意+推导讲解】1031 Hello World for U (20 分)_15行代码AC的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【讲解】1030 Travel Plan
- 下一篇: 【测试点三、四、五分析】1032 Sha