Meetings to be scheduled - 2023 Tianda & Nankai summer camp test questions

insert image description here

#include<bits/stdc++.h>
using namespace std;

int main(){
    
    
    ios::sync_with_stdio(false); cin.tie(nullptr);//加速cin, cout
    int T, n, s, t;
    cin >> T;
    while(T--){
    
    
        cin >> n;
        vector<pair<int, int>> vec;//<time,flag> flag=1开始/-1结束 
        for (int i = 0; i < n; ++i) {
    
    
            cin >> s >> t;
            vec.emplace_back(s, 1);
            vec.emplace_back(t, -1);
        }
        //首先按照时间点从小到大排序,然后按照会议状态的优先级排序(-1 优先于 1),以满足差分的要求。
        sort(vec.begin(), vec.end());
        int ans = 0, sum = 0;
        for (const auto& e : vec) {
    
    
            sum += e.second; //同时进行的会议数量sum,开始+1,结束-1
            ans = max(ans, sum); //维护一个sum的最大值
        }
        cout << ans << endl;
        vec.clear(); // 清空 vector
    }
    return 0;
}

Based on the entered meeting start and end times, the maximum number of simultaneous meetings needs to be determined.

Use a vector<pair<int, int>> to store the start and end times for each meeting, where the second element in the pair represents the state of the meeting (1 for start, -1 for end). emplace_back(make_pair(s, 1)) and emplace_back(s, 1) both create a new pair<int, int> object and add it to the end of the vector.

Next, the code sorts the vec, first by time point from smallest to largest, and then by the priority of the meeting state (-1 takes precedence over 1) 以满足差分的要求. After sorting, the start time and end time of meetings are arranged in order.

vector<pair<int, int>> vec uses the default operator< for sorting by default. For the pair type, the default comparison method is to compare the first element first and sort in ascending order, and if they are equal, compare the second element and sort in ascending order. Therefore, in sort(vec.begin(), vec.end()), the time points will be sorted from small to large first, and if the time points are the same, they will be sorted according to the priority of the conference status (-1 is prior to 1). Since this comparison method already meets the requirement of difference, there is no need to specially rewrite the comparison function.

Then, use a loop to traverse vec, and calculate the number of simultaneous meetings according to the change of the meeting state. By accumulating and updating the answers ans, the maximum number of simultaneous meetings can be obtained. ( 进行模拟: There are infinitely many meeting rooms, and the meeting operation is performed sequentially, the sum of the number of meeting rooms used at each moment is calculated, and the maximum value of a sum is maintained until all meetings are over)

Guess you like

Origin blog.csdn.net/weixin_54338498/article/details/131748796