1 条题解

  • 0
    @ 2023-4-16 21:41:26

    练38.2 大写字母 Y

    解题思路

    前n行按两条向中心靠拢的斜线输出,左右星号在i与2n-2-i列。第n行合并为一个中心星号,余下n-1行继续输出中心竖线。

    正确性说明

    计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。

    易错点

    总高度2n-1;最后一个星号后不补空格。

    复杂度

    时间O(n²),空间O(n)。

    参考代码(C++11)

    #include <bits/stdc++.h>
    using namespace std;
    
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(nullptr);
        int n;
        cin >> n;
        for (int i = 0; i < 2 * n - 1; i++) {
            if (i < n) {
                int right = 2 * n - 2 - i;
                cout << string(i, ' ') << "*";
                if (right > i)
                    cout << string(right - i - 1, ' ') << "*";
            } else
                cout << string(n - 1, ' ') << "*";
            cout << "\n";
        }
        return 0;
    }
    
    • 1

    信息

    ID
    263
    时间
    1000ms
    内存
    64MiB
    难度
    进阶
    标签
    递交数
    0
    已通过
    0
    上传者