二元矩阵峰值搜索
A farmer has built a long barn with N stalls. The stalls are placed in a straight manner at positions from x1, x2, ...xN. But his cows (C) are aggressive and don’t want to be near other cows. To prevent cows from hurting each other, he wants to place them in such a way so that the minimum distance between them is as large as possible. What is the largest minimum distance?
一位农民用N个摊位建造了一个长谷仓。 档位以直线方式放置在x1,x2,... xN处 。 但是他的母牛(C)具有攻击性,不想靠近其他母牛。 为了防止母牛互相伤害,他想以这样的方式放置它们,使它们之间的最小距离尽可能大。 最大最小距离是多少?
Constraints:
限制条件:
N: 2<=N<=100,000
C: 2<=C<=N
Xi: 0<=Xi<=1,000,000,000
Input:
输入:
Line1: Two integers N and C
Next N lines: An integer for Xi stall's position
Example:
例:
Input:
5 3
1 2 4 8 9
Output:
3
Explanation:
说明:
If the cows are placed at 1,4 and 9, it will result in minimum distance from 3.
如果将母牛放在1,4和9处,则距离3的距离最小。
SOLUTION AND CODE
解决方案和代码
Since the range of xi is from 0 to 10^9, one can say that the minimum distance between the cows will lie between the range. The minimum distance between 2 stalls can be 0 (lower bound) and maximum distance is 10^9 (upper bound). So, one can check for each value from lower bound to upper bound.
由于xi的范围是0到10 ^ 9,因此可以说母牛之间的最小距离将介于该范围之间。 2个档位之间的最小距离可以为0(下限),最大距离为10 ^ 9(上限)。 因此,可以检查从下限到上限的每个值。
Let's say for k minimum distance, we can check if it is possible to place cows in the stall. In case, you have reached the last stall but didn’t have placed all cows, then it is not possible else it is possible.
假设有k个最小距离,我们可以检查是否可以将奶牛放在摊位中。 万一您到达了最后一个摊位,但没有放完所有母牛,那么就不可能了。
A point to note is that if, for a k, it is possible to place the cows. Then all the values less than k will be true. Also, if k is false, then all the values greater than k will be false. We can say it is creating a monotonic function and we have to check for the transition from true to false and return that value.
需要注意的一点是,如果以ak为单位,则可以放置母牛。 那么所有小于k的值都将为真。 同样,如果k为假,则所有大于k的值都为假。 我们可以说它正在创建一个单调函数,我们必须检查从true到false的转换并返回该值。
It can be quickly and easily done with Binary Search from the range of 0 to 10^9.
使用Binary Search可以从0到10 ^ 9的范围内快速轻松地完成此操作。
CODE
码
#include <bits/stdc++.h>
using namespace std;
int N,C;
int check(int num,int stalls[])
{
int cows=1,pos=stalls[0];
for (int i=1; i<N; i++)
{
if (stalls[i]-pos>=num)
{
pos=stalls[i];
cows++;
if (cows==C)
return 1;
}
}
return 0;
}
int binarySearch(int stalls[])
{
int start=0,end=stalls[N-1],max=-1;
while (end>start)
{
int mid=(start+end)/2;
if (check(mid,stalls)==1)
{
if (mid>max)
max=mid;
start=mid+1;
}
else
end=mid;
}
return max;
}
int main()
{
int t;
cin>>t;
while (t--)
{
cin>>N>>C;
int stalls[N];
for (int i=0; i<N; i++)
cin>>stalls[i];
sort(stalls,stalls+N);
int k=binarySearch(stalls);
cout<<k;
}
return 0;
}
Output
输出量
翻译自: https://www.includehelp.com/data-structure-tutorial/aggressive-cows-on-binary-search.aspx
二元矩阵峰值搜索