c++ | Explain | Set
Upvote if you liked the solution\n\nI commented the code for better understanding\n\nIdea:\nThere can be 3 possible ways to position a person\n1. At the 0th ind
***Upvote if you liked the solution***\n\nI commented the code for better understanding\n\nIdea:\nThere can be 3 possible ways to position a person\n1. At the 0th index\n2. Somewhere in between\n3. At the end\n\nSo first check if 0th position is not present in the set? is yes place the person and return\nfor in between, take every consequetive pair of positions filled, calculate their middle and check if that is bigger than what we got \nfor end position check it after all this and if the closest distance is less than return\n\n```\nclass ExamRoom {\n    int n;\n    set<int>seats;\npublic:\n    ExamRoom(int N) {\n        n=N;\n    }\n    \n    int seat() {\n        // cur is the current empty position initialised with zero and will be updated in this function\n        // dist is the current maximum distance\n        int dist=0;\n        int cur=0;\n        \n        // is the seats is empty we can position the person on 0 seat\n        if(!seats.empty()){\n            auto it=seats.begin();\n            \n            // calculating initial \n            dist=*it;\n            \n            // doing this because we dont have any previous element to calculate the middle position\n            if(dist==0){\n                it++;\n            }\n            \n            // calculating the middle position for every pair of positioned person\n            while(it!=seats.end()){\n                \n                // calculating middle position\n                int mid=(*it-*(prev(it)))/2;\n                \n                // if the mid is grater than current grater distance than we found our new answer\n                // update dist and cur\n                if(dist<mid){\n                    dist=mid;\n                    \n                    // the new position will be mid steps away from prev(it)\n                    cur=*prev(it)+dist;\n                }\n                \n                // doing this till end\n                it++;\n            }\n            \n            // checking for the end position\n            if(dist<((n-1)-*(seats.rbegin()))){\n                cur=n-1;\n            }\n        }\n\n        // finally insert the cur into set\n        // return cur\n        seats.insert(cur);\n        return cur;\n    }\n    \n    void leave(int p) {\n        seats.erase(p);\n    }\n};\n```
['C', 'Ordered Set']