题解
一起来围长方形
1 条题解
-
0
解题思路
铁丝长度就是长方形的周长
n = 2×(长+宽),所以长+宽 = n/2。枚举宽x(从 1 开始),长就是n/2 - x,保证宽 ≤ 长就行。每找到一组就输出,最后输出组数。参考代码
#include <iostream> using namespace std; int main() { int n; cin >> n; int half = n / 2; // 长+宽 = 周长的一半 int cnt = 0; // 宽从1开始,保证宽<=长 for (int x = 1; x <= half / 2; x++) { int y = half - x; if (y >= x) { cout << x << " " << y << endl; cnt++; } } cout << cnt << endl; // 围法数量 return 0; }复杂度分析
枚举宽到 n/4,n 最大 1000,时间复杂度 O(n),额外空间复杂度 O(1)。
- 1