zoukankan      html  css  js  c++  java
  • 校门外的树2

    描述
    某校大门外长度为L的马路上有一排树,每两棵相邻的树之间的间隔都是1米。我们可以把马路看成一个数轴,马路的一端在数轴0的位置,另一端在L的位置;数轴上的每个整数点,即0,1,2,……,L,都种有一棵树。
    由于马路上有一些区域要用来建地铁。这些区域用它们在数轴上的起始点和终止点表示。已知任一区域的起始点和终止点的坐标都是整数,区域之间可能有重合的部分。现在要把这些区域中的树(包括区域端点处的两棵树)移走。你的任务是计算将这些树都移走后,马路上还有多少棵树。

    输入格式

    输入的第一行有两个整数L(1 <= L <= 1亿)和 M(1 <= M <= 20000),L代表马路的长度,M代表区域的数目,L和M之间用一个空格隔开。接下来的M行每行包含两个不同的整数,用一个空格隔开,表示一个区域的起始点和终止点的坐标。
    输出格式
    输出包括一行,这一行只包含一个整数,表示马路上剩余的树的数目。

    测试样例1

    输入
    500 3 
    150 300 
    100 200 

    470 471

    输出

    298

    分析:这道题原题上说是线段树,或许能做……但我开不了2亿的数组,于是暴力,快排,判重。

    代码如下:

    #include<iostream>
    #include<cstdio>
    #include<algorithm>
    using namespace std;
    
    struct note{
      int l,r;
    }tree[20002];
    
    int a,b;
    
    int cmp(note a,note b)
    {
     return a.l<b.l;
    }
    
    int main()
    {
     int n,m;
     scanf("%d%d",&n,&m);
     int ans=n+1;
     for (int i=1; i<=m; i++)
     {
      scanf("%d%d",&a,&b);
      tree[i].l=a; tree[i].r=b;
     }
     sort(tree+1,tree+m+1,cmp);
     for (int i=1; i<=m; i++)
     {
      for (int j=i+1; j<=m; j++)
      {
        if (tree[j].r<=tree[i].r) tree[j].r=tree[j].l-1;
        if (tree[j].r>tree[i].r && tree[j].l<=tree[i].r) tree[j].l=tree[i].r+1;
      }
     }
     for (int i=1; i<=m; i++) ans-=tree[i].r-tree[i].l+1;
     printf("%d
    ",ans);
     return 0;
    }
  • 相关阅读:
    131. Palindrome Partitioning
    130. Surrounded Regions
    129. Sum Root to Leaf Numbers
    128. Longest Consecutive Sequence
    125. Valid Palindrome
    124. Binary Tree Maximum Path Sum
    122. Best Time to Buy and Sell Stock II
    121. Best Time to Buy and Sell Stock
    120. Triangle
    119. Pascal's Triangle II
  • 原文地址:https://www.cnblogs.com/Shymuel/p/4393145.html
Copyright © 2011-2022 走看看