0
1
mirror of https://git.sb/baoshuo/OI-codes.git synced 2024-11-08 12:18:50 +00:00

P1147 连续自然数和

https://www.luogu.com.cn/record/165820608
This commit is contained in:
Baoshuo Ren 2024-07-13 22:57:59 +08:00
parent df2ee95279
commit bcf4b5e34e
Signed by: baoshuo
GPG Key ID: 00CB9680AB29F51A

View File

@ -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;
}