• D1. Too Many Segments (easy version)


    题目:样例1:

    输入
    1. 7 2
    2. 11 11
    3. 9 11
    4. 7 8
    5. 8 9
    6. 7 8
    7. 9 11
    8. 7 9

    输出
    3
    1 4 7 

    样例2:

    输入
    1. 5 1
    2. 29 30
    3. 30 30
    4. 29 29
    5. 28 30
    6. 30 30

    输出
    3
    1 2 4 

    样例3:

    输入
    1. 6 1
    2. 2 3
    3. 3 3
    4. 2 3
    5. 2 2
    6. 2 3
    7. 2 3

    输出
    4
    1 3 5 6 

    思路:

                    这里数据范围是 200,所以我们完全可以暴力遍历每一个点是否在该区间内,这里需要注意的是,可以通过差分的方式达到区间总和的变化,所以要学会掌握好差分。

    代码详解如下:

    1. #include
    2. #include
    3. #define endl '\n'
    4. #define YES puts("YES")
    5. #define NO puts("NO")
    6. #define umap unordered_map
    7. #pragma GCC optimize(3,"Ofast","inline")
    8. #define ___G std::ios::sync_with_stdio(false),cin.tie(0), cout.tie(0)
    9. using namespace std;
    10. const int N = 2e6 + 10;
    11. struct Range
    12. {
    13. int l,r;
    14. }a[N];
    15. int n,m;
    16. umap<int,int>b;
    17. umap<int,bool>r;
    18. inline void solve()
    19. {
    20. cin >> n >> m;
    21. for(int i = 1;i <= n;++i)
    22. {
    23. int l,r;
    24. cin >> l >> r;
    25. // 差分数组
    26. ++b[l];
    27. --b[r + 1];
    28. a[i] = {l,r};
    29. }
    30. // 差分前缀和,构造出每一个点所在位置的当前点前缀总和
    31. for(int i = 1;i <= 200;++i) b[i] += b[i - 1];
    32. int sz = 0; // 删除线段数量
    33. // 开始遍历每一个点
    34. for(int i = 1;i <= 200;++i)
    35. {
    36. // 如果当前线段所在的点有超过了规定可重合部分 m
    37. // 则开始选择删除
    38. while(b[i] > m)
    39. {
    40. int tem = 0; // tem 作为探头,探索哪一个需要删除的
    41. // 开始遍历每一个线段,寻找合适删除的线段
    42. for(int j = 1;j <= n;++j)
    43. {
    44. // 如果当前线段范围更广,那么应该删除,tem = j
    45. if(a[j].l <= i && a[j].r >= i && (!tem || a[j].r > a[tem].r) && !r[j]) tem = j;
    46. }
    47. // 标记已选择删除的线段
    48. r[tem] = true;
    49. // 累加删除线段
    50. ++sz;
    51. // 更新区间所在点的覆盖线段数量
    52. for(int j = a[tem].l;j <= a[tem].r;++j) --b[j];
    53. }
    54. }
    55. // 输出答案,删除的线段
    56. cout << sz << endl;
    57. for(int i = 1;i <= 200;++i)
    58. {
    59. if(r[i]) cout << i << ' ';
    60. }
    61. }
    62. int main()
    63. {
    64. // freopen("a.txt", "r", stdin);
    65. ___G;
    66. int _t = 1;
    67. // cin >> _t;
    68. while (_t--)
    69. {
    70. solve();
    71. }
    72. return 0;
    73. }

    最后提交:

  • 相关阅读:
    音视频从入门到精通——FFmpeg结构体:AVFrame分析
    Java8常用日期时间方法
    【imessage苹果群发推】通信协议TCP数据协议
    新超导光子电路
    AI、AIGC、AGI、ChatGPT它们的区别?
    Vue+springboot美发美容化妆品产品商城系统
    索引的创建、查看、删除
    FastAPI 学习之路(十六)Form表单
    平衡优化算法在特征选择中的应用(Matlab代码实现)
    vscode配置vim
  • 原文地址:https://blog.csdn.net/hacker_51/article/details/132746239