【问题标题】:Minimum cabs required (Algorithm)所需的最少驾驶室(算法)
【发布时间】:2019-10-27 12:08:58
【问题描述】:

我正在尝试解决这个问题:

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;

}

有人可以向我解释一下这个算法吗?

【问题讨论】:

  • 您好@nz_21,如果它解决了您的用例,您能否接受我的回答。它是一个很好的灵感

标签: c++ algorithm


【解决方案1】:

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

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

假设一个时间尺度,它代表时间:

Min time: 00:00 => 表示时间刻度上的 0

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

所以,作者使用了一个常数MAX 为1500,从而使时间尺度为[0, 1500],满足我们的要求。

现在,对于我们从输入中获得的每个间隔/范围,作者使用前缀和,从而将范围内的每个时间单位加 1。

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

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

希望这会有所帮助。随时提出任何疑问。如果满足您的疑问,请标记答案正确。

【讨论】:

    【解决方案2】:
    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);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多