PTA (Basic Level) 1027. Print hourglass

This question asks you to write a program to print a given symbol into an hourglass shape. 17 example given, "*", the following format printing requires

*****
 ***
  *
 ***
*****

The so-called "hourglass shape" refers to each row outputs odd symbols; symbol center of each row are aligned; the difference between the number of symbols two adjacent rows 2; the number of symbols in descending order of descending to the first one, then the order of small to large increments; inclusive symbol equal numbers.

Given any N symbols, not necessarily exactly composed of an hourglass. Requirements can be printed out as much of the hourglass symbol.

Input formats:

Input gives a positive integer N (≤1000) and a symbol in a row, separated by a space.

Output formats:

First print largest hourglass shape consisting of a given symbol, the symbol number output last remaining useless fall in a row.

Sample input:
19 *
Sample output:
*****
 ***
  *
 ***
*****
2
Thinking
  • Talk about derivation:
    • In addition to setting the middle *height of the outer sides are both \ (n-\)
    • In fact, both sides are arithmetic sequence: Finally, we can get the total number of stars on the height \ (n \) expression: \ (f (the n-) = the n-2 * * * the n-the n-+ 4 + 1 \)
    • Obviously the above function is an increasing function, as long as from i=0the beginning of the enumeration will be able to approach the lower limit
    • The rest is to control the output format, and down two triangles are actually about the same code are inverse process
    • The largest one of the largest pit ❗-- behind characters with no spaces, otherwise there will be two test pointsPE
Code
#include<bits/stdc++.h>
using namespace std;
int get_height(int x)
{
    for(int i=0;;i++)
    {
        int star_cnt = 2*i*i + 4*i + 1;
        if(star_cnt > x)
            return i-1;
    }
}
int main()
{
    int all;
    char ch;
    cin >> all;
    getchar();
    cin >> ch;
    if(all == 0)
    {
        cout << 0;
        return 0;
    }
    int height = get_height(all);
    int longest_star = 2*height + 1;
    for(int i=1;i<=height;i++)
    {
        for(int j=2;j<=i;j++) cout << " ";
        for(int k=1;k<=longest_star;k++)    cout << ch;
        longest_star -= 2;   //为2的等差数列
        cout << endl;
    }

    longest_star = 2*height + 1;
    for(int i=1;i<=(longest_star-1)/2;i++)  cout << " ";
    cout << ch << endl;

    longest_star  = 3;
    for(int i=height;i>=1;i--)
    {
        for(int j=2;j<=i;j++) cout << " ";
        for(int k=1;k<=longest_star;k++)    cout << ch;
        longest_star += 2;   //为2的等差数列
        cout << endl;
    }
    cout << all - (2*height*height + 4*height + 1);
    return 0;
}
Quote

https://pintia.cn/problem-sets/994805260223102976/problems/994805294251491328

Guess you like

Origin www.cnblogs.com/MartinLwx/p/11614224.html