所需最少驾驶室(算法)

Minimum cabs required (Algorithm)

本文关键字:算法 驾驶室      更新时间:2023-10-16

我正试图解决这个问题:

https://www.hackerearth.com/practice/algorithms/greedy/basics-of-greedy-algorithms/practice-problems/algorithm/minimum-cabs-0798cfa5/description/

我在这里看到了一个解决方案,但我不太明白

#include <bits/stdc++.h>
using namespace std;
const int MAX = 1500;
int A[MAX];
int main(int argc, char* argv[])
{
if(argc == 2 or argc == 3) freopen(argv[1], "r", stdin);
if(argc == 3) freopen(argv[2], "w", stdout);
ios::sync_with_stdio(false);
int n, hh1, hh2, mm1, mm2, smins, emins, ans;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> hh1 >> mm1 >> hh2 >> mm2;
smins = hh1 * 60 + mm1;
emins = hh2 * 60 + mm2;
A[smins]++;
A[emins+1]--;
}
ans = A[0];
for (int i = 1; i < MAX; i++) {
A[i] += A[i-1];
ans = max(ans, A[i]);
}
cout << ans << endl;
return 0;
}

有人能给我解释一下算法吗?

给定的解决方案适用于最大重叠间隔。

作者想计算在时间的任何给定点重叠的间隔或范围的最大数量。

假设一个表示时间的时间标度:

最短时间:00:00=>表示时间刻度上的0

最长时间:23:59=>表示时间刻度上的1439

因此,作者使用常数MAX作为1500,从而使时间标度为[01500],这满足了我们的要求。

现在,对于我们从输入中得到的每个区间/范围,作者使用前缀sum,从而在范围中的每个时间单位上加1。

例如:假设我的范围是00:00到12:36,那么我将在数组A的0到756的每个索引上加1。

最大前缀总和表示所需的出租车的最小数量,因为在任何特定的时间情况下,一辆出租车只能分配给一个人

希望这能有所帮助。请随时提出任何疑问。若您有疑问,请将答案标记为正确。

class TestClass
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int arr[] = new int[24*60+1];
while(t!=0)
{
int st = sc.nextInt()*60+sc.nextInt();
int et = sc.nextInt()*60+sc.nextInt();
for(int i=st;i<=et;i++)
{
arr[i]++;
}
t--;
}
int max=0;
for(int i=0;i<arr.length;i++)
{
max=Math.max(max,arr[i]);
}
System.out.println(max);
}
}