POJ-2456
Farmer John has built a new long barn, with N (2 <= N <= 100,000) stalls. The stalls are located along a straight line at positions x1,...,xN (0 <= xi <= 1,000,000,000).
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
His C (2 <= C <= N) cows don't like this barn layout and become aggressive towards each other once put into a stall. To prevent the cows from hurting each other, FJ want to assign the cows to the stalls, such that the minimum distance between any two of them is as large as possible. What is the largest minimum distance?
Input
* Line 1: Two space-separated integers: N and C
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
* Lines 2..N+1: Line i+1 contains an integer stall location, xi
Output
* Line 1: One integer: the largest minimum distance
Sample Input
5 3 1 2 8 4 9
Sample Output
3
Hint
OUTPUT DETAILS:
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
FJ can put his 3 cows in the stalls at positions 1, 4 and 8, resulting in a minimum distance of 3.
Huge input data,scanf is recommended.
题解:求解距离最小值可以取到的最大值(最小值的最大化)
AC代码为:

1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 5 6 using namespace std; 7 8 9 int main() 10 { 11 int N,C,left,right,mid; 12 13 cin>>N>>C; 14 15 int a[100005]; 16 17 for(int i=0;i<N;i++) 18 { 19 cin>>a[i]; 20 } 21 22 sort(a,a+N); 23 24 left=1,right=a[N-1]; 25 26 while(right>left+1) 27 { 28 29 mid=(left+right)/2; 30 31 int cns=0; 32 33 for(int i=0;i<N;) 34 { 35 int x=i; 36 while(a[++i]-a[x]<mid); 37 cns++; 38 } 39 if(cns>=C) 40 { 41 left=mid; 42 } 43 else 44 { 45 right=mid; 46 } 47 48 } 49 50 if(left!=right) 51 { 52 int cns=0; 53 54 for(int i=0;i<N;) 55 { 56 int t=i; 57 58 while(a[++i]-a[t]<right); 59 cns++; 60 } 61 62 if(cns>=C) 63 left=right; 64 } 65 66 printf("%d\n",left); 67 68 return 0; 69 }
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步