【ZR #539. 【19普转提 4】和】题解

题目链接

题目

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

请按 \(L\) 从小到大的顺序输出所有区间。

思路

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

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

也就是:

\[(L+R)(R-L+1)=n\times 2 \]

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

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

总结

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

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

Code

// 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
*/

posted @ 2022-01-08 15:44  zhangtingxi  阅读(40)  评论(0编辑  收藏  举报