zoukankan      html  css  js  c++  java
  • [贪心][51nod] 1133 不重叠的线段

    1133 不重叠的线段 

    基准时间限制:1 秒 空间限制:131072 KB 分值: 10 难度:2级算法题

     收藏

     关注

    X轴上有N条线段,每条线段有1个起点S和终点E。最多能够选出多少条互不重叠的线段。(注:起点或终点重叠,不算重叠)。

    例如:[1 5][2 3][3 6],可以选[2 3][3 6],这2条线段互不重叠。

    Input

    第1行:1个数N,线段的数量(2 <= N <= 10000)
    第2 - N + 1行:每行2个数,线段的起点和终点(-10^9 <= S,E <= 10^9)

    Output

    输出最多可以选择的线段数量。

    Input示例

    3
    1 5
    2 3
    3 6

    Output示例

    2

    贪心算法 

    1.尾降序排序 

    2.线段长升序排序

    #include <iostream>
    #include <algorithm>
    using namespace std;
    struct lines
    {
    	long long fst, lst;
    }arr[10010];
    bool cmp(lines x, lines y)
    {
    	if(x.lst != y.lst)
    		return x.lst < y.lst;
    	else
    		return x.fst < y.fst;
    }
    int main()
    {
    	int n;
    	cin>>n;
    	for(int i = 0; i < n; i++)
    	{
    		cin>>arr[i].fst>>arr[i].lst;
    	}
    	sort(arr, arr + n, cmp);
    	long long end = - 1e11, ans = 0;
    	for(int i = 0; i < n; i++)
    	{
    		if(arr[i].fst >= end)
    		{
    			ans ++;
    			end = arr[i].lst;
    		}
    	}
    	cout<<ans<<endl;
    	return 0;
    }
  • 相关阅读:
    竞争冒险及其消除
    [C++]重复单词统计
    [C++]智能指针与常规new
    基于go的生产者消费者模型
    cin的返回对象
    为什么map对象不能使用stl中的sort函数
    opencv
    operator ->
    记一次源码分析
    iconfig1
  • 原文地址:https://www.cnblogs.com/zeolim/p/12270679.html
Copyright © 2011-2022 走看看