1. 程式人生 > >Atcoder 091/092 C 2D Plane 2N Points[掃描線]

Atcoder 091/092 C 2D Plane 2N Points[掃描線]

pac lose 隨機 onclick bound 最小 AI 分享 UC

昨晚打了第一場atcoder...這題卡了1h...今天聽課的時候聽到了一個極相似的題。。。

題意:給出2n個點的坐標(x,y) 前n個是紅點,剩下是藍點,當一個紅點的橫縱坐標都小於一個藍點的時候,他們可以匹配,求最大的匹配對數

按照橫坐標排序,排序後從右往左掃描,發現藍點將其縱坐標存入set中(因為已經按照橫坐標排序,所以不需要考慮橫坐標),發現紅點從set中找一個能跟這個點匹配的最小的點(lower_bound),註意set::lower_bound是O(logn)的,std::lower_bound在set中是O(n)的,因為set不支持隨機訪問

還能用二分圖匹配,但是數據範圍大了似乎只能用這種方法

技術分享圖片

技術分享圖片
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 typedef pair<int, int> pii;
 4 set<int>s;
 5 struct Node {
 6   int x, y, color;
 7   inline bool operator < (const Node & rhs) const {return x < rhs.x;}
 8 }Node[300];
 9 int n, ans;
10 int main(void){
11 scanf("%d", &n); 12 for(int i = 1; i <= n; ++i) scanf("%d%d", &Node[i].x, &Node[i].y), Node[i].color = 1; 13 for(int i = 1; i <= n; ++i) scanf("%d%d", &Node[i+n].x, &Node[i+n].y), Node[i+n].color = 2; 14 sort(Node+1, Node+1+n*2); 15 for(int i = 2*n; i >= 1
; --i) { 16 if (Node[i].color == 2) s.insert(Node[i].y); 17 else { 18 auto it = s.lower_bound(Node[i].y); 19 if (it != s.end()) s.erase(it), ans++; 20 } 21 } 22 cout << ans; 23 return 0; 24 }
View Code

Atcoder 091/092 C 2D Plane 2N Points[掃描線]