structEvent{intx;inty1;inty2;chartype;Event(intx,inty1,inty2,chartype):x(x),y1(y1),y2(y2),type(type){}};classSolution{public:intrectangleArea(vector<vector<int>>&rectangles){constexprintkMod=1'000'000'007;vector<Event>events;for(constvector<int>&r:rectangles){events.emplace_back(r[0],r[1],r[3],'s');events.emplace_back(r[2],r[1],r[3],'e');}sort(begin(events),end(events),[](constauto&a,constauto&b){returna.x<b.x;});longans=0;intprevX=0;vector<pair<int,int>>yPairs;for(constauto&[currX,y1,y2,type]:events){if(currX>prevX){constintwidth=currX-prevX;ans=(ans+width*getHeight(yPairs))%kMod;prevX=currX;}if(type=='s'){yPairs.emplace_back(y1,y2);sort(begin(yPairs),end(yPairs));}else{// Type == 'e'constautoit=find(begin(yPairs),end(yPairs),pair<int,int>(y1,y2));yPairs.erase(it);}}returnans%kMod;}private:longgetHeight(constvector<pair<int,int>>&yPairs){intheight=0;intprevY=0;for(constauto&[y1,y2]:yPairs){prevY=max(prevY,y1);if(y2>prevY){height+=y2-prevY;prevY=y2;}}returnheight;}};
classEvent{publicintx;publicinty1;publicinty2;publicchartype;publicEvent(intx,inty1,inty2,chartype){this.x=x;this.y1=y1;this.y2=y2;this.type=type;}}classSolution{publicintrectangleArea(int[][]rectangles){finalintkMod=1_000_000_007;List<Event>events=newArrayList<>();for(int[]r:rectangles){events.add(newEvent(r[0],r[1],r[3],'s'));events.add(newEvent(r[2],r[1],r[3],'e'));}Collections.sort(events,(a,b)->a.x-b.x);longans=0;intprevX=0;List<Pair<Integer,Integer>>yPairs=newArrayList<>();for(Evente:events){if(e.x>prevX){finalintwidth=e.x-prevX;ans=(ans+width*getHeight(yPairs))%kMod;prevX=e.x;}if(e.type=='s'){yPairs.add(newPair<>(e.y1,e.y2));Collections.sort(yPairs,Comparator.comparing(Pair::getKey));}else{// Type == 'e'yPairs.remove(newPair<>(e.y1,e.y2));}}return(int)(ans%kMod);}privatelonggetHeight(List<Pair<Integer,Integer>>yPairs){intheight=0;intprevY=0;for(Pair<Integer,Integer>pair:yPairs){finalinty1=pair.getKey();finalinty2=pair.getValue();prevY=Math.max(prevY,y1);if(y2>prevY){height+=y2-prevY;prevY=y2;}}returnheight;}}
classSolution:defrectangleArea(self,rectangles:List[List[int]])->int:events=[]forx1,y1,x2,y2inrectangles:events.append((x1,y1,y2,'s'))events.append((x2,y1,y2,'e'))events.sort(key=lambdax:x[0])ans=0prevX=0yPairs=[]defgetHeight(yPairs:List[Tuple[int,int]])->int:height=0prevY=0fory1,y2inyPairs:prevY=max(prevY,y1)ify2>prevY:height+=y2-prevYprevY=y2returnheightforcurrX,y1,y2,typeinevents:ifcurrX>prevX:width=currX-prevXans+=width*getHeight(yPairs)prevX=currXiftype=='s':yPairs.append((y1,y2))yPairs.sort()else:# Type == 'e'yPairs.remove((y1,y2))returnans%(10**9+7)