本文搬运自本人初中博客园博客,若图片加载不出来,可到原文查看:https://www.cnblogs.com/zhangtingxi/p/15778449.html

题目链接

题目

给定一个数字 NN,请问有哪些区间 [L,R][L,R] 使得 i=LRi=N\sum_{i=L}^R i=N

请按 LL 从小到大的顺序输出所有区间。

思路

根据题意我们可以列出方程:

(L+R)(RL+1)2=n\frac{(L+R)(R-L+1)}{2}=n

也就是:

(L+R)(RL+1)=n×2(L+R)(R-L+1)=n\times 2

于是我们可以枚举 nn 的因数 xx,令 y=nxy=\frac n x,判断是否有两数和为 yy,差为 xx 即可。(这里假设 x<yx<y

枚举因数是 O(sqrtn)O(sqrt n),判断 O(1)O(1),固总时间复杂度 O(sqrtn)O(sqrt n)

总结

这题是一条非常经典的推式子+分解因数,只要把式子列出来发现规律就行了。

这种题在比赛是遇到一定不要慌,慢慢写出来,注意细节即可。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// Problem: D. 【19普转提 4】简单MST
// Contest: UOJ - 丽泽普及2022交流赛day8
// URL: http://zhengruioi.com/contest/1074/problem/542
// Memory Limit: 512 MB
// Time Limit: 5000 ms
//
// Powered by CP Editor (https://cpeditor.org)

#include<bits/stdc++.h>
using namespace std;
#define int long long
inline int read(){int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;
ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+
(x<<3)+(ch^48);ch=getchar();}return x*f;}
//#define N
//#define M
//#define mo
int n, m, i, j, k;
int x, y, l, r;

signed main()
{
// freopen("tiaoshi.in","r",stdin);
// freopen("tiaoshi.out","w",stdout);
n=read()*2;
for(x=sqrt(n); x>=1; --x)
if(n%x==0)
{
y=n/x;
l=(y-x+1)/2;
r=l+x-1;
if(l+r==y&&l!=r)
printf("%lld %lld\n", l, r);
}
return 0;
}
/*
(l+r)*(r-l+1)/2=n
(l+r)*(r-l+1)=n*2
l+r-(r-l+1)=l+r-r+l-1=2l-1
l=(x-y+1)/2
r=l+y
*/