题解:P1147 连续正整数和

· · 题解

题目链接:P1147

题目大意

给定一个正整数 M,求所有满足

## 大致思路 ### 无论你是暴力大神 注意到我们可以按题意使用循环暴力枚举 $l,r$ 并判断,将符合要求的 $l,r$ 输出。为避免超时,需要剪枝。 ### 前缀和大师 又注意到我们可以用前缀和优化对当前枚举到的 $l,r$ 的判断,这可以减少大量时间开销。 ### 还是数学大佬 双注意到我们可以使用等差数列求和公式求出区间 $[l,r]$ 内所有正整数的和: $$\frac{(r-l+1)(l+r)}{2}$$ 由此可得: $$(r-l+1)(l+r)=2M$$ 令 $k=r-l+1$,则 $r=l+k-1$。代入并化简可得: $$l=\frac{2M+k-k^2}{2k}$$ 可证: ::::info[$2M \bmod k=0$,$\frac{2M}{k}-k+1$ 是正偶数]{open} 注意到 $k(2l+k-1)=2M$,即: $$2l=\frac{2M}{k}-k+1$$ **(注意该式在代码中会被应用)** 显然有: $$2M \bmod k=0$$ $$\frac{2M}{k}-k+1 \bmod 2=0$$ $$0<\frac{2M}{k}-k+1$$ :::: ::::info[$1 \le k \le \frac{-1+\sqrt{1+8M}}{2}$] 由 $l \in \mathbb{N}^{+}$,显然有: $$\frac{2M+k-k^2}{2k}≥1$$ 解得: $$1 \le k \le \frac{-1+\sqrt{1+8M}}{2}$$ :::: 于是可以按条件枚举 $k$,若 $k$ 满足要求,输出 $l,r$ 即可。 ### 又或是双指针大佬 叒注意到我们可以用双指针尺取法解决本题,此处不过多介绍。 ## 最终代码 ::::error[错误写法]{open} 如前所述,若使用暴力写法,不剪枝会喜提 TLE。 ```cpp #include<bits/stdc++.h> using namespace std; int m; int main() { ios::sync_with_stdio(false); cin.tie(nullptr); cin>>m; for(int r=1;r<=m/2+1;r++) for(int l=1;l<r;l++) if((r-l+1)*(l+r)==2*m) cout<<l<<' '<<r<<endl; //当区间和大于m时没有剪枝导致超时,就算用前缀和也救不回来 return 0; } ``` :::: ### Code 1 ::::success[无论你是暴力大神] ```cpp #include<bits/stdc++.h> using namespace std; int m; int main() { cin>>m; for(int l=1;l<=m/2+1;l++) { int cnt=0; for(int r=l;r<m;r++) { cnt+=r; if(cnt>m) break; //如果不对cnt>m的情况判断会额外进行很多次计算,最终导致超时 if(cnt==m) { cout<<l<<' '<<r<<endl; break; } } } return 0; } ``` 时间复杂度:$\mathcal{O}(M)
空间复杂度:\mathcal{O}(1)
### Code 2
::::success[前缀和大师]
```cpp
#include<bits/stdc++.h>
using namespace std;
int m,a[2000005];
int f(int l,int r)
{
return a[r]-a[l-1];
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>m;
for(int i=1;i<=m/2+1;i++) a[i]=a[i-1]+i;
for(int l=1;l<=m/2+1;l++)
{
for(int r=l;r<m;r++)
{
if(f(l,r)>m) break;
if(f(l,r)==m)
{
cout<<l<<' '<<r<<endl;
break;
}
}
}
return 0;
}
```
时间复杂度:\mathcal{O}(M)
空间复杂度:\mathcal{O}(M)
::::
### Code 3
::::success[还是数学大佬]
```cpp
#include<bits/stdc++.h>
using namespace std;
int m;
void find(int m)
{
int k_max=int((sqrt(8*m+1)-1)/2);
for(int k=k_max;k>=2;k--)
//由于 k 递增时 l 递减,因此需要倒序枚举才能保证输出从小到大
//至少需要两个数,因此 k 枚举到 2 即可,否则当 l=r=m 时需要特判
{
int temp=(2*m)/k-k+1,l=temp/2,r=l+k-1;
//有关内容请见上文数学推导
if((2*m)%k==0&&temp>0&&!(temp&1)) cout<<l<<' '<<r<<endl;
//temp&1 此处相当于 temp%2,需要对结果取否
}
return;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>m;
find(m);
return 0;
}
```
时间复杂度:\mathcal{O}(\sqrt{M})
空间复杂度:\mathcal{O}(1)
::::
### Code 4
::::success[又或是双指针大佬]
```cpp
#include <bits/stdc++.h>
using namespace std;
int m,cnt=3;
//l,r 最少分别为 1,2,因此 cnt 初始值为 3
int main()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
cin>>m;
for(int l=1,r=2;l<r;)
{
if(cnt==m) cout<<l<<' '<<r<<endl,cnt-=l,l++;
else if(cnt<m) r++,cnt+=r;
else cnt-=l,l++;
}
return 0;
}
```
时间复杂度:\mathcal{O}(M)
空间复杂度:\mathcal{O}(1)
::::