1. 程式人生 > >51Nod 1091 線段重疊 貪心 區間重疊

51Nod 1091 線段重疊 貪心 區間重疊

quest ack blog ref lan include cmp cout names

按左端點排序,然後維護右端點最大值,貪心的思想。。。明明線掃一遍O(n)就好……然額……還是想得有些復雜

51Nod 1091 線段重疊 傳送門

#include<iostream>   
#include<algorithm>
#include<vector> 
#include<string.h>
#include<stack>
using namespace std;
typedef long long ll;
const int MAX = 5e4 + 5;
int n;
struct line {
    int l, r;
}a[MAX];
bool cmp(line a, line b) { if (a.l == b.l) return a.r > b.r; return a.l < b.l; } int main() { ios::sync_with_stdio(false); while (cin >> n) { for (int i = 0; i < n; i++) cin >> a[i].l >> a[i].r; sort(a, a + n, cmp);
int maxx=0,e=a[0].r; for (int i = 1; i < n; i++) { maxx = max(maxx, min(e, a[i].r) - a[i].l); //當前和之前相比較小的右端點-當前左端點 e = max(e, a[i].r); //維護右端點最大值 } cout << maxx << endl; } return 0; }

51Nod 1091 線段重疊 貪心 區間重疊