From bcf4b5e34e49a2db76cd6bab47b1779e3b7a3e2e Mon Sep 17 00:00:00 2001 From: Baoshuo Date: Sat, 13 Jul 2024 22:57:59 +0800 Subject: [PATCH] =?UTF-8?q?P1147=20=E8=BF=9E=E7=BB=AD=E8=87=AA=E7=84=B6?= =?UTF-8?q?=E6=95=B0=E5=92=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit https://www.luogu.com.cn/record/165820608 --- Luogu/P1147/P1147.cpp | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) diff --git a/Luogu/P1147/P1147.cpp b/Luogu/P1147/P1147.cpp index d5740004..aae8017f 100644 --- a/Luogu/P1147/P1147.cpp +++ b/Luogu/P1147/P1147.cpp @@ -2,22 +2,27 @@ using std::cin; using std::cout; -#define endl '\n' +const char endl = '\n'; -int m, sum, j; +int m; int main() { std::ios::sync_with_stdio(false); + cin.tie(nullptr); + cin >> m; - for (int i = 1; i <= m / 2; i++) { - sum = 0; - for (j = i; j < m; j++) { - sum += j; - if (sum >= m) break; - } - if (sum == m) { + + // 为什么到 m/2 结束?因为 m/2 之后的数不可能连着取两个数之和等于 m。 + for (int i = 1, j = 2, sum = 3 /* 初始 1 + 2 = 3 */; i <= (m >> 1);) { + if (sum == m) { // 够了,输出答案,并且把左面的数从窗口中删去 cout << i << ' ' << j << endl; + sum -= i++; // 压行:sum -= i; i++; + } else if (sum < m) { // 不够,需要往后再取一个数 + sum += ++j; // 压行:j++; sum += j; # 注意:这里是先加 j 再加 sum,顺序要写对 + } else { // sum > m # 多了,把左面的数从窗口中删去 + sum -= i++; // 压行:sum -= i; i++; } } + return 0; }