PAT 解题报告 1031. Hello World for U (20)

题目描述:

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.

算法分析:

就是个简单的模拟题, 寻找一下规律就知道该输出多少空格就好了, 代码如下:

int main(void) {

    string s;
    cin>>s;
    int N = s.length();
    int n1 = (N+2)/3;
    int n2 = N+2 - 2*n1;
    for(int i=0; i<n1-1; i++) {
        cout<<s[i];
        for(int j=1; j<=n2-2; j++)
            cout<<" ";
        cout<<s[N-1-i]<<endl;
    }
    for(int i=0; i<n2; i++) {
        cout<<s[n1-1+i];
    }
    cout<<endl;
    return 0;

}

注意点:

无特殊注意点.

(全文完,原创文章,转载时请注明作者和出处)


(转载本站文章请注明作者和出处 烟客旅人 sigmainfy — http://www.sigmainfy.com,请勿用于任何商业用途)

Written on August 2, 2013