利用二分思想:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; typedef long long ll; const int MAXN=1000000; int a[MAXN]; int N,M; bool calc(int mid){ int last=0; for(int i=1;i<M;i++){ int crt=last+1; while(crt<N&&a[crt]-a[last]<mid) crt++; if(crt==N) return false; last=crt; } return true; } void solve(){ sort(a,a+N); int right=a[N-1],left=0; while(right-left>1){ int mid=(right+left)/2; if(calc(mid)) left=mid; else right=mid; } printf("%d ",left); } int main(){ while(cin>>N>>M){ for(int i=0;i<N;i++) cin>>a[i]; solve(); } }