51nod 1091 線段的重疊 (貪心)

51nod 1091 線段的重疊

題目

給出 nn 條線段,問任意兩條線段最大重疊區間長度。n<5e4n < 5e4

分析

貪心,先按起點升序,終點降序排序,之後掃一遍所有區間。由於按起點升序,所以後面的區間起點一定小於前面的,因此對於當前區間,維護出現過的最遠右端點 pospos,考慮吧 pospos 與當前區間的相對位置跟新答案即可。
O(logn+n)O(logn + n)

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll INF = 0x3f3f3f3f;
const int N = 5e4 + 10;

int n;
struct node {
    int x, y;
    bool operator < (const node& b) const {
        if(x == b.x) return y > b.y;
        return x < b.x;
    }
}a[N];

int main() {
    cin >> n;
    for (int i = 0; i < n; i++) {
        cin >> a[i].x >> a[i].y; 
    }
    sort(a, a + n);
    int limit = -1, ans = 0;
    for (int i = 0; i < n; i++) {
        if (limit >= a[i].y) {
            ans = max(ans, a[i].y - a[i].x); 
        }
        if(limit > a[i].x && limit < a[i].y) {
            ans = max(ans, limit - a[i].x);
        }
        limit = max(limit, a[i].y);
    }
    cout << ans << "\n";
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章