安全警报启动的最小剩余时间
- 最后更新 : 2021年8月6日
Geek正在组织一场有N个自行车手的自行车比赛。第一名骑车者的初始速度用H表示i Km/小时,第1个骑车人的加速度为A****i Km/Hr2。速度为**"L "或更高的车手被认为是一个快速车手。每小时赛道上的总速度是由该小时内每个快速骑行者的速度相加计算出来的。当轨道上的总速度达到或超过每小时'M'**公里时,安全警报就会打开。任务是找出安全警报启动的最小小时数。
例子。
**输入。**N = 3, M = 400, L = 120, H = {20, 50, 20}, A = {20, 70, 90}
**输出。**3
解释:
所有骑车人在第i小时的速度:
Biker1 = [20 40 60 80 100]
Biker2 = [50 120 190 260 330]
Biker3 = [20 110 200 290 380]。轨道上的初始速度=0,因为骑车人的速度都不够快。
第一小时后轨道上的速度=120。
第二小时后轨道上的速度=190+200=390。
第三小时后轨道上的速度=260+290。
报警将在第三小时开始。**输入。**N = 2, M = 60, L = 120, H = {50, 30}, A = {20, 40}
**输出。**3
办法。如果自行车有一个初始速度U和一个均匀的加速度A,那么任何时间点的速度都可以通过二进制搜索来解决这个问题。(V=U+A*t),如果在某个时间点上,条件满足,那么对于所有大于t的时间点,都将满足,所以放弃右半部分的范围,直到找到最小值。按照下面的步骤来解决这个问题。
- 定义一个函数 **check(long H[], long A[], long mid, long N, long M, long L)**并执行以下步骤。
- 初始化变量,如low为0,high为1010,作为答案的二进制搜索范围,ans为0,存储最小小时数。
- 迭代直到low <= high,并执行以下步骤。
- 找到mid的值为**(low + high)/2**。
- 调用函数 check(H, A, mid, N, M, L),如果函数返回的值至少是M,那么将ans的值更新为mid。否则,将high的值更新为**(mid - 1)**。
- 否则,将low的值更新为**(mid + 1)**。
- 执行上述步骤后,将ans的值打印为结果的小时数。
下面是上述方法的实现。
C++
// C++ program for the aboce approach
#include <bits/stdc++.h> using namespace std;
// Function to check if the value of // mid as the minimum number of hours // satisfies the condition long check( long H[], long A[], long mid,
long N, long M, long L) {
// Stores the sum of speed
long sum = 0;
// Iterate over the range [0, N]
for ( long i = 0; i < N; i++) {
// Find the value of speed
long speed = mid * A[i] + H[i];
// If the bike is considered
// to be fast add it in sum
if (speed >= L) {
sum += speed;
}
}
// Return the resultant sum
return sum; }
// Function to find the minimum number // of time required long buzzTime( long N, long M, long L,
long H[], long A[]) {
// Stores the range of Binary Search
long low = 0, high = 1e10;
// Stores the minimum number of
// time required
long ans = 0;
while (high >= low) {
// Find the value of mid
long mid = low + (high - low) / 2;
// If the mid is the resultant
// speed required
if (check(H, A, mid,
N, M, L)
>= M) {
// Update the ans and high
ans = mid;
high = mid - 1;
}
// Otherwise
else
low = mid + 1;
}
// Return the minimum number of hours
return ans; }
// Driver Code int main() {
long M = 400, L = 120;
long H[] = { 20, 50, 20 };
long A[] = { 20, 70, 90 };
long N = sizeof (A) / sizeof (A[0]);
cout << buzzTime(N, M, L, H, A);
return 0; } |
输出。
3
**时间复杂度:**O(N*log(max(L, M)))
辅助空间。O(1)
读者请注意!现在不要停止学习。掌握所有重要的DSA概念。 DSA自学课程以适合学生的价格掌握所有重要的DSA概念,并成为行业的准备者。 要完成从学习语言到DS Algo以及更多的准备工作,请参考 完整的面试准备课程.
如果你想参加专家的现场课程 ,请参考 面向在职人士的DSA现场课程 和 面向学生的竞争性编程直播.
我的个人笔记 arrow_drop_up
保存