【问题标题】:Insert and Search in Segment tree在段树中插入和搜索
【发布时间】:2014-03-11 19:07:23
【问题描述】:

所以问题是这样的,我们有一个数组,我们应该做两种类型的操作:

1) 在段 [x,y] 上添加值 v,

2) 在段 [x,y] 上求和

我正在寻找答案,但找不到任何东西,如果您有任何有用的链接或建议,我将不胜感激。

【问题讨论】:

    标签: c++ segment-tree


    【解决方案1】:

    这两种赋值都可以通过使用标准算法和 lambda 表达式来完成,或者实际上通过使用基于范围的 for 语句来实现。

    使用算法和 lambda 表达式的方法

    #include <algorithm>
    
    std::for_eqch( std::begin( a ), std:;end( a ),
                   [=]( int &z ) { if ( x <= z && z <= y ) z += v; } );
    
    #include <numeric>
    
    int sum = std::accumulate( std::begin( a ), std::edn( a ), 0,
                               [=]( int acc, int z ) { return acc + ( x <= z && z <= y ? z : 0 ); } );
    

    使用基于范围的方法

    for ( int &z : a )
    {
       if ( x <= z && z <= y ) z += v;
    }
    
    int sum = 0;
    
    for ( int z : a )
    {
       if ( x <= z && z <= y ) sum += z;
    }
    

    事实上,你可以使用任何形式的循环来完成分配。:)

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 2012-04-10
      • 2012-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多