Hello World for U
Posted Mel年
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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: 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 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. 输入: There are multiple test cases.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. 样例输入: helloworld! ac.jobdu.com 样例输出: h ! e d l l lowor a m c o . c jobdu.
-
题目本身不难,在做的过程中遇到了三个问题
1.由于第一次尝试用c++写,虽然跟c语言相差无几,但是有需要注意的细节。用到了string类,需要引入cstring包,但是VC引入string包才能编译通过,在OJ上只能是ctring才能编译通过
2.由于n1 = n3 = max { k| k <= n2 for all 3 <= n2 <= N },也就是说n1,n2,n3三个数可以相等,所以在判断的时候要加n1<=n2
3.又由于n2>=3的,最开始做的时候没看到等号,直接让n2从4开始的,导致当n=5的时候出现了错误
修正三个错误后的代码如下:(其中n1,n2分别表示了题目中的n1,n3;x表示题目中的n2)
#include <iostream> #include <cstring> #inculde <cstdio> using namespace std; int main(){ char arr[80]; int x; int i,j; int n1,n2; while(scanf("%s",arr)!=EOF){ int n = strlen(arr); for(x=3;x<n;x++){ if((n+2-x)%2==0&&(n+2-x)/2<=x) break; } n1=n2=(n+2-x)/2; for(i=0;i<n1-1;i++) { cout<<arr[i]; for(j=0;j<x-2;j++) cout<<" "; cout<<arr[n-i-1]; cout<<"\n"; } for(i=0;i<x;i++) { cout<<arr[n1-1+i]; } cout<<"\n"; } return 0; }
-
以上是关于Hello World for U的主要内容,如果未能解决你的问题,请参考以下文章