愤怒的牛&数列分段II
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 using namespace std; 5 const int maxn=1e5+7; 6 int n,m; 7 int l,r,mid; 8 int xx[maxn]; 9 bool check(int u){ 10 int cnt=1;int lft=xx[1]+u; 11 for(int i=2;i<=n;i++){ 12 if(lft<=xx[i]) {cnt++;lft=xx[i]+u;} 13 } 14 return cnt>=m; 15 } 16 int main(){ 17 cin>>n>>m; 18 for(int i=1;i<=n;i++) cin>>xx[i]; 19 sort(xx+1,xx+n+1); 20 l=0;r=xx[n]-xx[1]; 21 while(l<=r){ 22 mid=(l+r)/2; 23 if(check(mid)) l=mid+1; 24 else r=mid-1; 25 } 26 cout<<r<<endl; 27 return 0; 28 }
如果不是l=mid+1,r=mid-1的话,因为这里都是整数,很可能出现l=mid的情况,这是就会无限循环下去
数列分段II
1 #include<iostream> 2 #include<cstdio> 3 using namespace std; 4 typedef long long ll; 5 const ll maxn=1e6+7; 6 ll n,m,l,r,mid; 7 ll a[maxn]; 8 bool check(ll x){ 9 ll cnt=1;ll lft=a[1]; 10 for(ll i=2;i<=n;i++){ 11 if(lft+a[i]>x){cnt++;lft=a[i];} 12 else{lft+=a[i];} 13 } 14 return cnt<=m; 15 } 16 int main(){ 17 cin>>n>>m; 18 for(ll i=1;i<=n;i++) {cin>>a[i];r+=a[i];l=max(l,a[i]);} 19 while(l<=r){ 20 mid=(l+r)/2; 21 if(check(mid)) r=mid-1; 22 else l=mid+1; 23 } 24 cout<<l<<endl; 25 return 0; 26 }
l不能设成0