紫书 习题 8-15 UVa 1617 (贪心)

先排序, 然后每个线段先放右端点, 然后往下放, 如果不能放就整体往左移动, 当不能往左移动的时候就ans++

开始下一个整块。判断能不能向左移动要用一个变量储存每个已经放了的区间中线段与左端点距离的最小值。

#include<cstdio>
#include<algorithm>
#define REP(i, a, b) for(int i = (a); i < (b); i++)
using namespace std;

const int MAXN = 112345;
struct node
{
	int l, r;
	bool operator < (const node& x) const
	{
		return l < x.l || (l == x.l && r < x.r);
	}
}a[MAXN];

int main()
{
	int T, n;
	scanf("%d", &T);
	
	while(T--)
	{
		scanf("%d", &n);
		REP(i, 0, n) scanf("%d%d", &a[i].l, &a[i].r), a[i].r--; //0到3区间, 实际上只有01, 12可以放 
		sort(a, a + n);
		
		int start = a[0].r, limit = start - a[0].l, ans = 0; //limit表示还能往左移的值。start表示当先线段的位置 
		REP(i, 1, n)
		{
			start++;
			if(start < a[i].l) { ans++; start = a[i].r; limit = start - a[i].l; }
			else if(start <= a[i].r) limit = min(limit, start - a[i].l);
			else
			{
				while(limit >= 0 && start > a[i].r) start--, limit--;
				if(limit < 0)
				{
					ans++;
					start = a[i].r;
					limit = start - a[i].l;
				}
			}
		}
			
		printf("%d\n", ans);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_34416123/article/details/80270724