关于STL黑科技
加上头文件 #include <numeric>
加上头文件 #include <functional>
废话不多说,直接上代码:
数组求和
加和
sum = 0;
for(int i = 0;i < n;++i)
sum += a[i];
printf("%d", sum);
等价于
printf("%d", accumulate(a, a + n, 0));
乘积
sum = 1;
for(int i = 0;i < n;++i)
sum *= a[i];
printf("%d", sum);
等价于
printf("%d", accumulate(a, a + n, 1, multiplies<int>()));
异或和
for(int i = 0;i < n;++i)
sum ^= a[i];
printf("%d", sum);
等价于
printf("%d", accumulate(a, a + n, 0, [](int a, int b){return a ^ b;}));
差分
减法
for(int i = 1;i <= n;++i)
d[i] = a[i] - a[i - 1];
等价于
adjacent_difference(a + 1, a + n + 1, d + 1);
除法
for(int i = 1;i <= n;++i)
d[i] = a[i] * inv[a[i - 1]] % M;
等价于
adjacent_difference(a + 1, a + n + 1, d + 1, [](int a, int b){return a * inv[b] % M;});
异或
for(int i = 1;i <= n;++i)
d[i] = a[i] ^ a[i - 1];
等价于
adjacent_difference(a + 1, a + n + 1, d + 1, [](int a, int b){return a ^ b;});
奇怪的式子
考虑计算 $\sum\limits_{i=1}^na_ib_i$
sum = 0;
for(int i = 1;i <= n;++i)
sum += a[i] * b[i];
printf("%d", sum);
等价于
printf("%d", inner_product(a + 1, a + n + 1, b + 1, 0));
前缀和
加和
for(int i = 1;i <= n;++i)
s[i] = s[i - 1] + a[i];
等价于
partial_sum(a + 1, a + n + 1, s + 1);
乘积
for(int i = 1;i <= n;++i)
s[i] = s[i - 1] * a[i];
等价于
partial_sum(a + 1, a + n + 1, s + 1, multiplies<int>());
异或
for(int i = 1;i <= n;++i)
s[i] = s[i - 1] ^ a[i];
等价于
partial_sum(a + 1, a + n + 1, s + 1, [](int a, int b){return a ^ b;});
数组初始化
for(int i = 1;i <= n;++i)
a[i] = i;
等价于
iota(a + 1, a + n + 1, 1);