[英]Confusion with signed and unsigned int
我正在尝试使用Fenwick tree从这里解决这个问题。 我的代码如下:
class BIT {
public:
BIT(std::vector<int> list) {
m_array = std::vector<int>(list.size() + 1, 0);
for (int idx = 0; idx < list.size(); idx++) {
update(idx, list[idx]);
}
}
int prefix_query(int idx) const {
int result = 0;
for (++idx; idx > 0; idx -= idx & -idx) {
result += m_array[idx];
}
return result;
}
int range_query(int from_idx, int to_idx) const {
// Computes the range sum between two indices (both inclusive)
if (from_idx == 0)
return prefix_query(to_idx);
else
return prefix_query(to_idx) - prefix_query(from_idx - 1);
}
void update(int idx, int add) {
// Add a value to the element at index idx
for (++idx; idx < m_array.size(); idx += idx & -idx) {
m_array[idx] += add;
}
}
private:
std::vector<int> m_array;
};
int main () {
int n, q, a, b, c;
std::cin >> n >> q;
std::vector<int> vec(n+1);
for(int i = 1; i < n + 1; i++){
std::cin >> a;
vec.push_back(a);
}
BIT bit(vec);
for(int i = 0; i < q; i++){
std::cin >> b >> c;
std::cout << bit.range_query(b, c) << std::endl;
}
}
我尝试使用(signed) idx
将 idx 转换为带符号的数字,但是当我这样做时,代码会为我输入的任何值返回 0。 我不明白出了什么问题,因为它在我的机器上运行良好,但在线判断中的 C++ 编译器在提出任何有用的建议方面并不是很有帮助。
std::vector::size
通常是size_t
类型,它是无符号的。 因此,将 idx 强制转换或声明为无符号类型应该可以修复编译器警告。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.