1023. Arranging DominoesProblem code: ADOMINO |
Dominoes have long entertained both game enthusiasts and programmers for quite some time. Many games can be played with dominoes, including multiplayer and single player games. Hari Khan has come up with a single player game. He takes N boxes and arranges them in a row at positions N1, N2 ... NN. Now he has to place D dominoes (D <= N) in the boxes such that the minimum distance between any two filled boxes is maximized.
The first line of the input contains an integer t, the number of test cases. t test cases follow.
The first line of each test case consists of two integers, N <= 100000 and D <= N, separated by a single space.
N lines follow, each containing a single integer Ni <= 1000000000, indicating the location of the ith box.
For each test case, output a single line containing a single integer denoting the largest minimum distance achievable between any two boxes with dominoes.
Input: 1 5 3 1 2 3 4 5 Output: 2 最小值最大化;常见思路二分; 二分思路,列举可能的的最佳min—maxmum(假定最佳值为该值);o(n)判断是否可行; 然后二分逼近最优值; 逼近时,一,要用右边界为最终值,一旦右边界满足条件,即终止;#include <iostream> #include <cstring> #include <cstdio> #include <algorithm> using namespace std; const int maxn = 100100; int a[maxn],n,M; int Judge(int min_maxmum){ int counter=0; int Left=a[0]; int i; for(i=0;i<n;i++){ if(a[i]-Left>=min_maxmum) { counter++; Left=a[i]; if(counter==M) break; } } if(counter<M) return -1; return 1; } int main() { int T; scanf("%d",&T); while(T--){ scanf("%d %d",&n,&M); for(int i=0;i<n;i++) scanf("%d",&a[i]); sort(a,a+n); M-=1; int x=a[0],y=a[n-1],res; while(x<y){ int m=(x+y)>>1; if(x==m&&Judge(x)) {y=x; break;} int ok=Judge(m); if(ok==-1) y=m-1; else x=m; if(Judge(y)==1) break; } printf("%d\n",y); } return 0; }