Skip to content

Instantly share code, notes, and snippets.

@jxu
Last active November 11, 2024 17:19
Show Gist options
  • Save jxu/9a5cf1fb29d93b75500cdb4b93e0ff6e to your computer and use it in GitHub Desktop.
Save jxu/9a5cf1fb29d93b75500cdb4b93e0ff6e to your computer and use it in GitHub Desktop.
Comparing C and C++ data structure impl https://godbolt.org/z/hnEvd8Wx1
#include <vector>
#include <iostream>
struct fenwick_tree {
size_t len; // 0-based len
std::vector<long long> t; // 1-based tree, indexes [1:len]
fenwick_tree(std::vector<long long> const &a)
{
len = a.size();
t.assign(len + 1, 0);
for (size_t i = 0; i < len; ++i)
add_to(i, a[i]);
}
long long sum_to(size_t r)
{
long long s = 0;
for (++r; r > 0; r -= r & -r)
s += t[r];
return s;
}
void add_to(size_t i, long long delta)
{
for (++i; i <= len; i += i & -i)
t[i] += delta;
}
};
int main()
{
std::vector<long long> a(10, 1);
fenwick_tree ft(a);
for (int i = 0; i < 10; ++i)
std::cout << ft.sum_to(i) << " ";
}
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
typedef long long* fenwick_tree; // plain array data structure
long long fenwick_sum_to(fenwick_tree ft, size_t r)
{
long long s = 0;
for (++r; r > 0; r -= r & -r)
s += ft[r];
return s;
}
// len is the length of the original 0-based array
void fenwick_add_to(fenwick_tree ft, size_t len, size_t i, long long delta)
{
for (++i; i <= len; i += i & -i)
ft[i] += delta;
}
// array can init globally if size is known
fenwick_tree fenwick_init(long long a[], size_t len)
{
fenwick_tree ft = calloc(len + 1, sizeof(long long));
for (size_t i = 0; i < len; ++i)
fenwick_add_to(ft, len, i, a[i]);
return ft;
}
int main()
{
long long a[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
fenwick_tree ft = fenwick_init(a, 10);
for (int i = 0; i < 10; ++i)
printf("%lld\n", fenwick_sum_to(ft, i));
}
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
typedef struct {
size_t len; // 0-based len
long long* t; // 1-based tree, indexes [1:len]
} fenwick_tree;
long long fenwick_sum_to(fenwick_tree ft, size_t r)
{
long long s = 0;
for (++r; r > 0; r -= r & -r)
s += ft.t[r];
return s;
}
// len is the length of the original 0-based array
void fenwick_add_to(fenwick_tree ft, size_t i, long long delta)
{
for (++i; i <= ft.len; i += i & -i)
ft.t[i] += delta;
}
fenwick_tree fenwick_init(long long a[], size_t len)
{
fenwick_tree ft;
ft.len = len;
ft.t = calloc(len + 1, sizeof(long long));
for (size_t i = 0; i < len; ++i)
fenwick_add_to(ft, i, a[i]);
return ft;
}
int main()
{
long long a[10] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};
fenwick_tree ft = fenwick_init(a, 10);
for (int i = 0; i < 10; ++i)
printf("%lld\n", fenwick_sum_to(ft, i));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment