zoukankan      html  css  js  c++  java
  • hihocoder-Weekly223-Interval Coverage

    hihocoder-Weekly223-Interval Coverage

    题目1 : Interval Coverage

    时间限制:10000ms
    单点时限:1000ms
    内存限制:256MB

    描述

    You are given N intervals [S1, T1], [S2, T2], [S3, T3], ... [SN, TN] and a range [X, Y]. Select minimum number of intervals to cover range [X, Y].

    输入

    The first line contains 3 integers N, X and Y. (1 <= N <= 100000, 1 <= X < Y <= 1000000)

    The following N lines each contain 2 integers Si, Ti denoting an interval. (1 <= Si < Ti <= 1000000)

    输出

    Output the minimum number of intevals to cover range [X, Y] or -1 if it is impossible.

    样例输入
    5 1 5
    1 2    
    1 3  
    2 4  
    3 5  
    4 5 
    样例输出
    2

      题解:

        参考:http://hihocoder.com/discuss/question/5567

        使用贪心算法。对所有的interval上的排序之后,根据interval进行尽可能向后的选择。

    #include <cstdio>  
    #include <cstring> 
    #include <cstdlib>   
    
    const int MAXN = 100000 + 10; 
    
    struct Node
    {
    	int x, y; 
    }nd[MAXN]; 
    int n, x, y; 
    
    #define max(a, b) (a)>(b)?(a):(b) 
    
    int cmp(const void *a, const void *b)
    {
    	Node *aa = (Node *)a; 
    	Node *bb = (Node *)b; 
    	if(aa->x == bb->x)
    	{
    		return (aa->y - bb->y); 
    	}
    	return aa->x - bb->x; 
    }
    
    int main(){ 
    
        scanf("%d %d %d", &n, &x, &y);   
    
        int max_y = 0;  
        for(int i=0; i<n; ++i)
        {
        	scanf("%d %d", &nd[i].x, &nd[i].y); 
        	max_y = max(max_y, nd[i].y);  
        } 
        qsort(nd, n, sizeof(Node), cmp);  
    
        if(n <= 0 || nd[0].x > x || max_y < y)
        {
        	printf("-1
    ");
        }else{
        	int tmp_y=0, cnt = 1, start = x, end = 0; 
        	for(int i=0; i<n; ++i)
        	{
        		if(nd[i].y < start)
        		{
        			continue; 
        		} 
        		if(nd[i].x <= start)
        		{
        			tmp_y = max(tmp_y, nd[i].y);   
        		}else if(nd[i].x > end)
        		{
        			break; 
        		}else{
        			start = tmp_y;  
        			tmp_y = nd[i].y; 
        			++cnt; 
        		}
        		end = max(end, nd[i].y); 
        		if(end >= y)
        		{
        			break; 
        		}
        	}
        	if(end >= y)
        	{
        		printf("%d
    ", cnt);
        	}else{
        		printf("-1
    ");
        	} 
        } 
        return 0; 
    } 
    
  • 相关阅读:
    操作系统01_进程和线程管理
    数据库02_字段类型
    鲁滨逊漂流记游戏
    查找数N二进制中1的个数(JS版 和 Java版)
    js中的call、apply
    jQuery对象与Dom对象的相互转换
    jndi配置数据源
    关于JS中变量的作用域-实例
    重写equals()方法时,需要同时重写hashCode()方法
    String与StringBuilder
  • 原文地址:https://www.cnblogs.com/zhang-yd/p/9782941.html
Copyright © 2011-2022 走看看