1. 程式人生 > >Codeforces 597B Restaurant(離散化 + 貪心)

Codeforces 597B Restaurant(離散化 + 貪心)

ces struct lower c++ 排好序 bit ont scanf sin

題目鏈接 Restaurant

題目意思就是在n個區間內選出盡可能多的區間,使得這些區間互不相交。

我們先對這n個區間去重。

假如有兩個區間[l1, r1],[l2, r2]

若滿足l1 >= l2且 r1 <= r2,那麽[l2, r2]就是可以被去掉的。

因為這兩個區間裏我們顯然最多只能選擇一個。

如果我們在答案裏選擇了[l2, r2],那麽我們如果把[l2, r2]換成[l1, r1]的話

這個答案肯定還是滿足題意的。

甚至可能騰出了可以放下其他區間的空間。

那麽我們去重之後進行離散化,接下來就是貪心的過程。

我們把這些處理好的區間以左端點為關鍵字升序排序。

排好序的區間,右端點肯定也是升序的。

我們預處理出f[i]為右端點小於等於i的所有區間的編號的最大值。

我們從最後一個區間開始選,

對於當前我們可以選擇的範圍肯定要選擇編號更大的。

因為編號越大說明左端點越大,給其他區間留出的空間越多。

於是我們從最後一個區間開始選,依次貪心,這樣就可以了。

#include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b)	for (int i(a); i <= (b); ++i)
#define dec(i, a, b)	for (int i(a); i >= (b); --i)

typedef long long LL;

const int inf = 1e9 + 1;
const int N = 1e6 + 10;
const int A = 22;

struct node{
	int x, y, s, t;
	friend bool operator < (const node &a, const node &b){
		return a.x == b.x ? a.y < b.y : a.x < b.x;
	}
} a[N], c[N];


int b[N << 2], d[N << 2];
int cnt, tot, now;
int n, m, et;
int mx;
int st[N << 1][A];
int ans;

bool cmp(const node &a, const node &b){
	return a.s == b.s ? a.t > b.t : a.s < b.s;
}	

int main(){

	scanf("%d", &n);
	cnt = 0;
	rep(i, 1, n){
		int x, y;
		scanf("%d%d", &a[i].x, &a[i].y);
		a[i].s = a[i].y;
		a[i].t = a[i].x + inf;
	}

	sort(a + 1, a + n + 1, cmp);

	cnt = 0;
	for (int i = 1, j; i <= n;){
		j = i + 1;
		while (j <= n && a[j].t <= a[i].t) ++j;
		c[++cnt] = a[i];
		i = j;
	}


	et = 0;
	rep(i, 1, cnt){
		b[++et] = c[i].x;
		b[++et] = c[i].y;
	}

	rep(i, 1, et) d[i] = b[i];
	sort(d + 1, d + et + 1);
	tot = unique(d + 1, d + et + 1) - d - 1;
	rep(i, 1, et) b[i] = lower_bound(d + 1, d + tot + 1, b[i]) - d;
	et = 0;
	rep(i, 1, cnt){
		c[i].x = b[++et];
		c[i].y = b[++et];
	}

	mx = c[cnt].y;
	
	rep(i, 1, mx){
		if (i < c[1].y) continue;
		int l = 1, r = cnt;
		while (l + 1 < r){
			int mid = (l + r) >> 1;
			if (c[mid].y <= i) l = mid;
			else r = mid - 1;
		}

		if (c[r].y <= i) st[i][0] = r;
		else st[i][0] = l;

	}


	now = mx;
	ans = 0;
	for (; now > 0; ){
		int fl = st[now][0];
		if (fl == 0) break;
		++ans;
		now = c[fl].x - 1;
	}

	printf("%d\n", ans);
	return 0;


}

Codeforces 597B Restaurant(離散化 + 貪心)