1 条题解
-
0
【例38.3】 X战警
解题思路
第i行的X在列i与n-1-i,其他列为空格。只输出到这两列中较大的那一列,避免末尾多余空格。
正确性说明
计算规则直接来自题目定义。按所述顺序处理时,已完成部分的结果被准确保存在累加量、计数或当前状态中;下一步只加入新增贡献。最终得到完整要求的结果。
易错点
中心两条对角线重合,只输出一个X。
复杂度
时间O(n²),空间O(1)。
参考代码(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 < n; i++) { int last = max(i, n - 1 - i); for (int j = 0; j <= last; j++) cout << (j == i || j == n - 1 - i ? 'X' : ' '); cout << "\n"; } return 0; }
- 1