题解:P1147 连续正整数和
题目链接:P1147
题目大意
给定一个正整数
| 空间复杂度: |
|---|
| ### 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; |
| } |
| ``` |
| 时间复杂度: |
| 空间复杂度: |
| :::: |
| ### 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; |
| } |
| ``` |
| 时间复杂度: |
| 空间复杂度: |
| :::: |
| ### 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; |
| } |
| ``` |
| 时间复杂度: |
| 空间复杂度: |
| :::: |