Editorial for Tổng dãy con
Remember to use this editorial only when stuck, and not to copy-paste code from it. Please be respectful to the problem author and editorialist.
Submitting an official solution before solving the problem yourself is a bannable offence.
Submitting an official solution before solving the problem yourself is a bannable offence.
Ý tưởng bài này là sử dụng tổng tiền tố. Đặt \(s[i] = a[1] + a[2] + ... + a[i]\). Ta có thể tính mảng \(s\) trong một vòng for như sau:
s[0] = 0
for i = 1..n
s[i] = s[i - 1] + a[i]
Lưu ý tổng \(a[l] + ... + a[r] = (a[1] + a[2] + ... + a[r]) - (a[1] + a[2] + ... + a[l - 1]) = s[r] - s[l - 1]\).
Như vậy ta có thể tính mỗi truy vấn trong \(O(1)\).
Comments