#include <functional>
#include <array>
#include <concepts>
#include <iostream>
#include <limits>
constexpr int __MAX__ { static_cast<int>( 1e4 ) * 2 };
constexpr int lowbit(signed x) noexcept {
return std::bit_and<signed> {}(x, std::negate<signed> {}(x));
}
template <typename T, typename... U>
concept all_of_same_as = (std::same_as<T, U> && ...);
//初始化
template <typename... Args>
auto convert(Args ...args)
requires (all_of_same_as<signed, Args...>){
constexpr auto length { static_cast<int>(sizeof...(Args)) };
constexpr auto place_holder { std::numeric_limits<signed>::min() };
std::array<signed, length + 1> from {place_holder, args...};
std::array<long long signed, length + 1> transformed { {place_holder, 0, } };
for(auto i {1}; i <= length; ++i)
for(auto j {i - lowbit(i) + 1}; j <= i; ++j)
transformed[i] += from[j];
return transformed;
}
//前缀和
template <std::size_t Size>
constexpr auto prefix(std::array<long long signed, Size> const & transformed, int p) noexcept{
long long signed result {};
for(; p; p -= lowbit(p)) result += transformed[p];
return result;
}
//区间和
template <std::size_t Size>
constexpr auto range_sum(std::array<long long signed, Size> const & transformed, int p, int q) noexcept{
return prefix(transformed, q) - prefix(transformed, p - 1);
}
//单点修改
template <std::size_t Size>
constexpr void single_modify(std::array<long long signed, Size> & transformed, int p, int x) noexcept{
for(; p < static_cast<int>(Size); p += lowbit(p)) transformed[p] += x;
}
//测试
int main(void){
auto result { convert(1, 2, 3, 4, 5, 6, -3) };
for(auto e : result) std::cout << e << ' ';
endl(std::cout);
std::cout << prefix(result, 3);
endl(std::cout);
single_modify(result, 1, 1);
for(auto e : result) std::cout << e << ' ';
endl(std::cout);
std::cout << range_sum(result, 1, 4);
return 0;
}
【树状数组 | 简单实现】(单点修改 | 区间查询)
最新推荐文章于 2024-11-17 21:01:47 发布