思路:有点类似于找最大值的最小化。
代码及解析
常规的模板引用40%
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll N=1e5+3;
ll a[N];
ll m,n;
ll chack(ll mid)
{int res=1,last=0;for(int i=1;i<n;i++){ if(a[i]-a[last]>=mid){res++;last=i;}}return res;
}//
int main()
{ll left=0,right=1e9+3,mid;cin>>n>>m;for(int i=0;i<n;i++){cin>>a[i];}sort(a,a+n);//二分算法一定要记得排序 while(left<right){mid=(left+right)/2;if(chack(mid)<m){right=mid-1; }else{left=mid;}}cout<<left<<endl;return 0;
}
100%
#include <bits/stdc++.h>
using namespace std;
#define ll long long
const ll N=1e5+3;
ll a[N];
ll m,n;
ll chack(ll mid)
{int res=1,last=0;for(int i=1;i<n;i++){ if(a[i]-a[last]>=mid){res++;last=i;}}return res;
}//
int main()
{ll left=0,right=1e9+3,mid;cin>>n>>m;for(int i=0;i<n;i++){cin>>a[i];}sort(a,a+n);//二分算法一定要记得排序 while(left+1!=right){mid=(left+right)/2;if(chack(mid)<m){right=mid; }else{left=mid;}}cout<<left<<endl;return 0;
}