C++ Solution | Offline query solving | Set
\nclass cmp{\npublic:\n    bool operator()(vector<int>& a,vector<int>& b){\n        if(a[1]==b[1]) return a[0]<b[0];\n        return a[1]<b[1];\n    }\n};\nclas
```\nclass cmp{\npublic:\n    bool operator()(vector<int>& a,vector<int>& b){\n        if(a[1]==b[1]) return a[0]<b[0];\n        return a[1]<b[1];\n    }\n};\nclass Solution {\npublic:\n    vector<int> closestRoom(vector<vector<int>>& a, vector<vector<int>>& q) {\n        int n=a.size(),m=q.size();\n        vector<vector<int>> b(m);\n        for(int i=0;i<m;i++){\n            b[i]={q[i][1],q[i][0],i};\n        }\n        vector<int> ans(m,-1);\n        sort(b.begin(),b.end());\n        sort(a.begin(),a.end(),cmp());\n        int i=n-1;\n        set<int> id;\n        for(int j=m-1;j>=0;j--){\n            while(i>=0 && b[j][0]<=a[i][1]){\n                id.insert(a[i][0]);\n                i--;\n            }\n            auto l=id.upper_bound(b[j][1]);\n            auto r=id.upper_bound(b[j][1]);\n            int lv=-1,rv=-1;\n            if(l!=id.begin()){\n                l=prev(l);\n                lv=*l;\n            }\n            if(r!=id.end()){\n                rv=*r;\n            }\n            if(lv!=-1 && rv!=-1){\n                if(abs(b[j][1]-lv)==abs(b[j][1]-rv)) ans[b[j][2]]=lv;\n                else if(abs(b[j][1]-lv)<abs(b[j][1]-rv)) ans[b[j][2]]=lv;\n                else ans[b[j][2]]=rv;\n            }\n            else if(lv!=-1) ans[b[j][2]]=lv;\n            else if(rv!=-1) ans[b[j][2]]=rv;\n        }\n        return ans;\n    }\n};\n```
[]