题目来源
Hello World for U - PTA
Hello World for U - 牛客
Description
Given any string ofN ( ≥ 5 ) N (≥5)N(≥5)characters, you are asked to form the characters into the shape ofU. For example, helloworld can be printed as:
h d e l l r lowoThat is, the characters must be printed in the original order, starting top-down from the left vertical line withn 1 n_1n1characters, then left to right along the bottom line withn 2 n_2n2characters, and finally bottom-up along the vertical line withn 3 n_3n3characters. And more, we would likeUto be as squared as possible – that is, it must be satisfied thatn 1 = n 3 = m a x { k ∣ k ≤ n 2 for all 3 ≤ n 2 ≤ N } with n 1 + n 2 + n 3 − 2 = N n_1=n_3=max \{ k | k≤n_2 \text{ for all } 3≤n_2≤N \} \text{ with } n_1+n_2+n_3−2=Nn1=n3=max{k∣k≤n2 for all3≤n2≤N}withn1+n2+n3−2=N.
Input Specification:
Each input file contains one test case. Each case contains one string with no less than5 55and no more than80 8080characters in a line. The string contains no white space.
Output Specification:
For each test case, print the input string in the shape ofUas specified in the description.
Sample Input:
helloworld!Sample Output:
h ! e d l l lowor题目大意
给出一个字符串,要求按照U形输出该字符串U形的定义是:对于长为N NN的字符串,一共有n 1 = n 3 n_1=n_3n1=n3行,n 2 n_2n2列,满足n 1 + n 2 + n 3 − 2 = N n_1+n_2+n_3-2=Nn1+n2+n3−2=N,且n 1 = n 3 ≤ n 2 n_1=n_3\leq n_2n1=n3≤n2
输出顺序是左侧从上到下,然后底部从左到右,最后右侧从下到上
思路简介
看懂题目的公式后其实很简单
先计算n 2 n_2n2,不难发现,当N + 2 N+2N+2是3 33的倍数时,n 2 = ( N + 2 ) / 3 n_2=(N+2)/3n2=(N+2)/3
如果在此基础上,长度再多1 11,由于n 1 = n 3 ≤ n 2 n_1=n_3\leq n_2n1=n3≤n2,多出来的长度只能加到n 2 n_2n2上
长度多2 22同理
综上:n 2 = ( N + 2 ) / 3 + ( N + 2 ) % 3 n_2=(N+2)/3+(N+2)\%3n2=(N+2)/3+(N+2)%3
输出时,按照行输出,维护一个左指针l和一个右指针r
前n 1 − 1 n_1-1n1−1行,只输出开头和结尾,每次输入完后l--,r++,其他地方输出空格
最后一行从l输出到r即可
遇到的问题
- 无,一遍过
代码
/** * Hello World for U(20) * https://pintia.cn/problem-sets/994805342720868352/exam/problems/type/7?problemSetProblemId=994805462535356416 * 模拟 */#include<bits/stdc++.h>usingnamespacestd;voidsolve(){string s;cin>>s;intlen=s.size();intn2=(len+2)/3+(len+2)%3;intn1=(len+2-n2)/2;intl=0,r=len-1;for(inti=0;i<n1-1;++i){for(intj=0;j<n2;++j){if(j==0)cout<<s[l++];elseif(j==n2-1)cout<<s[r--]<<'\n';elsecout<<' ';}}for(inti=l;i<=r;++i){cout<<s[i];}cout<<'\n';}intmain(){ios::sync_with_stdio(0);cin.tie(0);cout.tie(0);//fstream in("in.txt",ios::in);cin.rdbuf(in.rdbuf());intT=1;//cin>>T;while(T--){solve();}return0;}