`

Minimum Number of Bus Stations / Meeting Rooms

 
阅读更多

Question: At a bus-station, you have time-table for buses arrival and departure. You need to find the minimum number of platforms so that all the buses can be accommodated as per their schedule.

Example: Time table is like below:

Bus         Arrival         Departure 
BusA        0900 hrs        0930 hrs
BusB        0915 hrs        1300 hrs
BusC        1030 hrs        1100 hrs
BusD        1045 hrs        1145 hrs


Then the answer must be 3. Otherwise the bus-station will not be able to accommodate all the buses.

Answer:
Let’s take the same example as described above. Now if we apply dynamic programming and calculate the number of buses at station at any time (when a bus comes or leaves). Maximum number in that pool will be nothing but the maximum number of buses at the bus-station at any time. That number is the minimum number of platforms required.

So first sort all the arrival(A) and departure(D) time in an int array. Please save the corresponding arrival or departure in the array also. Either you can use a particular bit for this purpose or make a structure. After sorting our array will look like this:

0900    0915    1930    1030    1045    1100    1145    1300
A       A       D       A       A       D       D       D


Now modify the array as put 1 where you see A and -1 where you see D. So new array will be like this:

1       1       -1      1       1       -1      -1      -1


And finally make a cumulative array out of this:

1       2       1       2       3       2       1       0


Your solution will be the maximum value in this array. Here it is 3.

I think that code for this will not be complex so I am skipping that part. The complexity of this solution depends on the complexity of sorting.

PS: If you have a arriving and another departing at same time then put departure time first in sorted array.

 
Further Thoughts: You don not need to create a cumulative array or an array with 1 and -1; you just need a counter (cnt) initialized at '0'. Whenever, you find an 'A' in arrival-departure array, increment cnt by 1. Compare it with maximum value (max); if it is greater than max, make max equal to cnt. If you get a 'D' in arrival-departure array, decrement cnt by 1. At the end, return 'max'.

 

Examples:

Input:  arr[]  = {9:00,  9:40, 9:50,  11:00, 15:00, 18:00}
        dep[]  = {9:10, 12:00, 11:20, 11:30, 19:00, 20:00}
Output: 3
There are at-most three trains at a time (time between 11:00 to 11:20)

 

// Returns minimum number of platforms reqquired
int findPlatform(int arr[], int dep[], int n)
{
   // Sort arrival and departure arrays
   sort(arr, arr+n);
   sort(dep, dep+n);
 
   // plat_needed indicates number of platforms needed at a time
   int plat_needed = 1, result = 1;
   int i = 1, j = 0;
 
   // Similar to merge in merge sort to process all events in sorted order
   while (i < n && j < n)
   {
      // If next event in sorted order is arrival, increment count of
      // platforms needed
      if (arr[i] < dep[j])
      {
          plat_needed++;
          i++;
          if (plat_needed > result)  // Update result if needed
              result = plat_needed;
      }
      else // Else decrement count of platforms needed
      {
          plat_needed--;
          j++;
      }
   }
 
   return result;
}

 

Time Complexity: O(nLogn), assuming that a O(nLogn) sorting algorithm for sorting arr[] and dep[].

或者下面这种写法,思路是一样的:

int min_rooms(vector<Interval>& meetings) {
    vector<int> times;
    for(auto m : meetings) {
        times.push_back(m.begin);
        times.push_back(-m.end);
    }   
    sort(times.begin(), times.end(), [](int a, int b){
        return abs(a) == abs(b) ? a < b : abs(a) < abs(b);
    });   
    int ret = 0, cur = 0;
    for(auto t : times) {
        if(t >= 0) ret = max(ret, ++cur);
        else --cur;
    }
    return ret;
}

 

The follow up question:

You have a number of meetings (with their start and end times). You need to schedule them using the minimum number of rooms. Return the list of meetings in every room.

 

The answer:

First we need to realize that randomly schedule meetings to available rooms won’t give you an optimal solution. For example, suppose there are 4 meetings, the (start, end) time are (1, 3), (1, 5), (6, 7), (4, 7). When (1, 3) comes, assign to room A, then (1, 5) comes, assign to room B, then (6, 7) comes, assign to room A as it is available, then (4, 7) comes, both room A and B are not available so we have to assign a new room C for it. However, a better solution is two rooms, room A for meeting (1, 3) (4, 7) and room B for meeting (1, 5) (6, 7).

However, the optimal solution solution is not far from it. If we first sort all the meeting by the start time, then we could just assign them one by one and to the first available room.

The reason is simple, when considering a meeting from s[i] to e[i], as there is no unschedule meeting before s[i], by putting the (s[i], e[i]) meeting in any available room (if there is one) would leads to the same results.

So the code looks like this.

void arrange(vector<pair> meeting) { // the pair contains the start and end time.
  sort(meeting.begin(), meeting.end());
  vector<vector<pair>> room; // for each room, there is a list of meetings.
  for (auto m : meeting) {
    bool found = False;
    for (auto& r : room) {
      if (m.first >= r.back().second) // we can arrange the meeting in the room
        r.push_back(m);
        found = True;
        break;
      }
    }
    if (!found) {
      room.push_back({m});
    }
  }
  cout << "Requires " << room.size() << " rooms" << endl;
  for (int i = 0; i < room.size(); ++i) {
    cout << "Room " << i << endl;
    for (auto m : room[i]) {
      cout << "Meeting: " << m.first << " " << m.second << endl;
    }
  }
}

 

References:

http://tech-queries.blogspot.com/2009/05/number-of-bus-stations.html

http://www.geeksforgeeks.org/minimum-number-platforms-required-railwaybus-station/

http://www.fgdsb.com/2015/01/30/meeting-rooms/

https://nuttynanaus.wordpress.com/2014/04/26/software-engineer-interview-questions-3/

https://hellosmallworld123.wordpress.com/2014/05/30/arranging-the-meeting-room/

分享到:
评论

相关推荐

    收音IC说明,bk1080

    space and minimum number of external components. All functions are controlled through a simple 3-wire serial interface or I2C serial interface. The device operates from a power supply of 2.7 – 5.5 ...

    中国邮路问题c语言代码

    The first line of input for each case contains two positive integers: n , the number of water stations, and m , the number of trails. For each trail, there is one subsequent line of input containing ...

    freight-app:货运.braveineve.com

    勇敢的集体货运网站: : 前端在webroot/js...stations/generate.py 中调整区域过滤器/站列表在./gen_stations/运行./cron.sh后端 - 合约在./gen_contracts/cron.sh 中编辑公司 API 密钥在./gen_contracts/运行./cron.sh

    On the 20/40 MHz Coexistence of Overlapping BSSs in WLANs

    when stations (STAs)/AP that operate in 20/40 MHz BSS are able to dynamically switch between 20 MHz and 40 MHz transmit/receive modes and CCA is used in the extension channel, the throughput of both ...

    moscow_bus_stations

    地面城市交通的站点地图 为应用程序“地面城市交通的站点地图”提供了现成的模板和... import_stations控制命令从moscow_bus_stations.csv文件加载数据 将数据从csv加载到db的命令 python manage.py import_stations

    shanghai-bus:上海公交信息API查询

    /api/v1/stations/&lt;string&gt;/&lt;int&gt;/ 查询车辆到站信息 /api/v1/stops/&lt;string&gt;/&lt;int&gt;/ 示例: 查询公交100上行站台信息 /api/v1/stations/up/110/ { "data": { "1": "吉浦路仁德路", "2": "武川路武东路", "3":...

    Deployment Analysis of cooperative OFDM base stations

    Deployment Analysis of cooperative OFDM base stations

    BikeStations_Microservice:Java,JPQL,Spring MVC,Spring Boot,Spring Data JPA,H2

    租用端点: PATCH / api / stations / borrow / {rentStationId} / {UserId} / {bikeSerialNumber} 归还自行车的端点: PATCH / api / stations / gback / {backStationId} / {UserId} BUILD'n'RUN项目: 对于Unix...

    stations-geojson:欧洲火车站的 GeoJSON 数据

    curl https://raw.githubusercontent.com/capitainetrain/stations/master/stations.csv &gt; stations.csv 将stations.csv文件通过管道stations.csv到脚本中,并将生成的 GeoJSON 传输到一个新文件中: stations2...

    SnailTime:SnailTime — Railtime.be API包装器

    / stations /:id /到达 特定车站的详细信息,仅到达 / stations /:id /出发 特定车站的详细信息(仅出发) /路线 要求从根特圣皮特斯到安特卫普中央的路线 本地化和i18n 通过在请求中提供定义的Accept-Language...

    Si2173-A30Rev1

    picture quality and a higher number of received stations in real-world conditions due to its very high linearity and low noise. Interfacing the Si2173 seamlessly with the Si2165 DVB-T/C demodulator ...

    Numerical Calculation of the Impact of Offshore Wind Power Stations on Hydrodynamic Conditions

    Numerical Calculation of the Impact of Offshore Wind Power Stations on Hydrodynamic Conditions,张玮,夏海峰,本文通过建立长江口、杭州湾及其附近海域大范围平面二维潮流数学模型,探讨上海风力发电场规划...

    Variation of E - layer critical frequency with solar activity

    Zurich relative sunspot number R, the solar radio noise flux $ at 10-7 cm and the ionospheric index of solar activity IF2, and numerical expressions are derived. There is no difference in the degree ...

    我的迪杰斯特拉算法小结

    迪杰斯特拉算法总结与代码描述 Problem Description One day , Kiki wants to visit one of her ... To make it easy, if the city have n bus stations ,the stations will been expressed as an integer 1,2,3…n.

    brail2stoptimes:[实验] 为比利时铁路创建一个 node.js 停止时间流

    比利时铁路 2 停止时间该项目... 1 停止时间看起来像这样: { "stop" : "http://irail.be/stations/NMBS/008821121#10" , "departureTime" : "2014-12-15T18:02:00Z" , "headsign" : "Antwerpen-Centraal" , "@id" : ...

    air-mission

    空气排放 链接: : ... 使用方法:在链接之后输入您要从中获取数据的路径 example --&gt;...to get all stations data 喂养 ./feed/stations GET-&gt;..../feed/stations/:ID GET-&gt;通过_ID获取特定的电台查询 认证 ./auth/s

    IEEE Std 802.3™-2008(Revision of IEEE Std 802.3-2005)Section 5

    and defines services and protocol elements that enable the exchange of IEEE Std 802.3 format frames between stations in a subscriber access network. Clause 68 specifies a 10 Gb/s physical layer ...

    Algorithmics - The Spirit of Computing

    Companies can no longer be run without them, and a growing number of sophisti- cated medical procedures cannot be performed in their absence. They serve lawyers and judges who seek judicial ...

    Python库 | covmatic-stations-2.12.8.tar.gz

    python库。 资源全名:covmatic-stations-2.12.8.tar.gz

Global site tag (gtag.js) - Google Analytics