能力有限,最后两个超时了,求优化。

P1147 连续自然数和

@[KKKZOZ](/user/60925) 求助大佬
by Mr_xiao @ 2023-02-26 16:24:08


这题最好双指针
by Patron_Saint @ 2023-02-26 16:33:22


楼上正解,算法没对,直接枚举每个区间时间复杂度太高了,建议用双指针来做
by KKKZOZ @ 2023-02-26 16:43:28


我为啥这样都能过?![](//图.tk/5) ```cpp #include<bits/stdc++.h> #include<cstdio> #include<cstring> using namespace std; int main() { int n,j; cin>>n; for(int i=1;i<=n-1;i++) { int s=0; for(j=i;s<n;j++) { s+=j; } if(s==n) cout<<i<<" "<<j-1<<endl; } return 0; } ```
by Silent_Ltcd_2024 @ 2023-02-26 17:09:19


@[Mr_xiao](/user/871152)
by Silent_Ltcd_2024 @ 2023-02-26 17:09:59


@[CSP_AK_zyz](/user/623291) ```java```速度慢
by da_ke @ 2023-02-26 17:10:10


@[WA_Coding_Duck](/user/766675) 这![](//图.tk/i)
by Silent_Ltcd_2024 @ 2023-02-26 17:12:56


好,我再试试
by Mr_xiao @ 2023-02-26 17:45:50


``` #include<iostream> #include<cmath> using namespace std; int n; int sum; /* 可以用双指针维护一个区间 如果总和sum小了,那么就让右端向右 否则就让左往左 */ int main(){ cin>>n; int l = 0,r = 0; while (l<=r && r<n){ if (sum<n){ r++; sum+=r; }else{ if(sum==n) cout<<l<<' '<<r<<endl; sum-=l; l++; } } return 0; } ```
by Lawliet142857 @ 2023-03-21 20:32:28


|