|
| 1 | + |
| 2 | +If the question was asking to display the number of people in every second, |
| 3 | + |
| 4 | +then one possible approach would be to maintain an array P, where P[i] holds the number of people at time i. |
| 5 | + |
| 6 | +Now, for each person, you could increment P[entry] .... P[exit] by one. |
| 7 | + |
| 8 | +This is O(|entry - exit| N) |
| 9 | + |
| 10 | +One way to optimise this is to write New People[entry]++, New People[exit]-- |
| 11 | + |
| 12 | +And then P[i] = P[i - 1] + New People[i] |
| 13 | + |
| 14 | +This is O(|entry - exit| + N). |
| 15 | + |
| 16 | +While this is a very cool trick for range queries, |entry - exit| is simply too big here (1e7) |
| 17 | + |
| 18 | +Now, I tried this and went through every second to see which i maximised P[i]. |
| 19 | + |
| 20 | +However, this will cause a TLE, needless to say. |
| 21 | + |
| 22 | +Instead, what should be done is keep track of the IDENTITY of each time - whether it is an entry or an exit. |
| 23 | +Sort all entries by time. |
| 24 | + |
| 25 | +If the identity is an entry, increment the no of people. Else decrement it. |
| 26 | + |
| 27 | +This is O(N log N + N) |
| 28 | + |
| 29 | +N log N for sorting + N for the people. |
| 30 | + |
| 31 | +This never takes too much time because the N log N <<< |entry - exit|. In fact, in this approach even if |entry - exit| = 1e18, nothing would change, |
| 32 | +it would still run as fast. |
| 33 | + |
| 34 | +Whenever an entry is logged, increment the counter. |
| 35 | +When an exit is logged, decrement the counter. |
| 36 | + |
| 37 | +This only depends on the number of logs and not the size of the interval. |
| 38 | + |
| 39 | +----------------------------------------------------- |
| 40 | + |
| 41 | +struct log{ |
| 42 | + int time, type; |
| 43 | +}; |
| 44 | + |
| 45 | +int compare(const log &A, const log &B) |
| 46 | +{ |
| 47 | + return (A.time <= B.time); |
| 48 | +} |
| 49 | + |
| 50 | +void solve() |
| 51 | +{ |
| 52 | + const int ENTRY = 0, EXIT = 1; |
| 53 | + |
| 54 | + int no_of_people; |
| 55 | + scanf("%d", &no_of_people); |
| 56 | + |
| 57 | + vector <log> event(2*no_of_people); |
| 58 | + |
| 59 | + for(int i = 0; i < no_of_people; i++) |
| 60 | + { |
| 61 | + scanf("%d %d", &event[2*i].time, &event[2*i + 1].time); |
| 62 | + |
| 63 | + event[2*i].type = ENTRY; |
| 64 | + event[2*i + 1].type = EXIT; |
| 65 | + } |
| 66 | + |
| 67 | + sort(all(event), compare); |
| 68 | + |
| 69 | + int no_of_inside_people = 0; |
| 70 | + int max_people = 0; |
| 71 | + |
| 72 | + for(int i = 0; i < event.size(); i++) |
| 73 | + { |
| 74 | + no_of_inside_people += (event[i].type == ENTRY ? 1 : -1); |
| 75 | + max_people = max(no_of_inside_people, max_people); |
| 76 | + } |
| 77 | + |
| 78 | + printf("%d\n", max_people); |
| 79 | +} |
| 80 | + |
0 commit comments