zoukankan      html  css  js  c++  java
  • 紫书 习题 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
    ", ans);
    	}
    	
    	return 0;
    }

  • 相关阅读:
    2020/5/8
    2020/5/8
    2020/5/6
    2020/4/30
    2020/4/29
    2020/4/28
    2020/4/27
    KMP算法详解
    博客搬家声明
    洛谷P2831 NOIP2016 愤怒的小鸟
  • 原文地址:https://www.cnblogs.com/sugewud/p/9819563.html
Copyright © 2011-2022 走看看