|
| 1 | +/// Source : https://leetcode.com/problems/time-taken-to-cross-the-door/description/ |
| 2 | +/// Author : liuyubobobo |
| 3 | +/// Time : 2023-01-14 |
| 4 | + |
| 5 | +#include <iostream> |
| 6 | +#include <vector> |
| 7 | +#include <queue> |
| 8 | + |
| 9 | +using namespace std; |
| 10 | + |
| 11 | + |
| 12 | +/// Event Simulation |
| 13 | +/// Time Compelxity: O(n) |
| 14 | +/// Space Complexity: O(n) |
| 15 | +class Solution { |
| 16 | +public: |
| 17 | + vector<int> timeTaken(vector<int>& arrival, vector<int>& state) { |
| 18 | + |
| 19 | + int n = arrival.size(); |
| 20 | + |
| 21 | + vector<int> res(n, -1); |
| 22 | + queue<int> enter_list, leave_list; |
| 23 | + int arrival_index = 0, t = 0, pre_state = -1; |
| 24 | + while(arrival_index < n || !enter_list.empty() || !leave_list.empty()){ |
| 25 | + while(arrival_index < n && arrival[arrival_index] <= t){ |
| 26 | + if(state[arrival_index] == 0) enter_list.push(arrival_index); |
| 27 | + else leave_list.push(arrival_index); |
| 28 | + arrival_index ++; |
| 29 | + } |
| 30 | + |
| 31 | + if(pre_state == -1 || pre_state == 1){ |
| 32 | + if(!leave_list.empty()){ |
| 33 | + int index = leave_list.front(); leave_list.pop(); |
| 34 | + res[index] = t; |
| 35 | + pre_state = 1; |
| 36 | + } |
| 37 | + else if(!enter_list.empty()){ |
| 38 | + int index = enter_list.front(); enter_list.pop(); |
| 39 | + res[index] = t; |
| 40 | + pre_state = 0; |
| 41 | + } |
| 42 | + else pre_state = -1; |
| 43 | + } |
| 44 | + else{ |
| 45 | + if(!enter_list.empty()){ |
| 46 | + int index = enter_list.front(); enter_list.pop(); |
| 47 | + res[index] = t; |
| 48 | + pre_state = 0; |
| 49 | + } |
| 50 | + else if(!leave_list.empty()){ |
| 51 | + int index = leave_list.front(); leave_list.pop(); |
| 52 | + res[index] = t; |
| 53 | + pre_state = 1; |
| 54 | + } |
| 55 | + else pre_state = -1; |
| 56 | + } |
| 57 | + t ++; |
| 58 | + } |
| 59 | + |
| 60 | + return res; |
| 61 | + } |
| 62 | +}; |
| 63 | + |
| 64 | + |
| 65 | +void print_vec(const vector<int>& res){ |
| 66 | + for(int e: res) cout << e << ' '; cout << '\n'; |
| 67 | +} |
| 68 | + |
| 69 | +int main() { |
| 70 | + |
| 71 | + vector<int> arrival1 = {0, 1, 1, 2, 4}, state1 = {0, 1, 0, 0, 1}; |
| 72 | + print_vec(Solution().timeTaken(arrival1, state1)); |
| 73 | + // 0 3 1 2 4 |
| 74 | + |
| 75 | + vector<int> arrival2 = {0,0,6,9,10,10,11,11,11,12,14,14,15,15,15,15,15,16,18,18}, |
| 76 | + state2 = {0,0,0,0,0,0,1,1,1,1,0,1,1,1,0,1,0,1,0,0}; |
| 77 | + print_vec(Solution().timeTaken(arrival2, state2)); |
| 78 | + // 0 3 1 2 4 |
| 79 | + |
| 80 | + return 0; |
| 81 | +} |
0 commit comments