---
id: 534
lang: en
translation_of: index.md
source_sha256: 8b38c9902d538299423a2ff9728ffa5482f345609a6f8f44f989f22f3c42c7cb
title: "BZOJ1176: [Balkan2007] Mokia — Solution"
description: "With a huge w and 2D sums to answer, use a nested data structure: a Fenwick tree of balanced BSTs instead of dynamic segment trees, to save space."
tags: ["OI","Segment Tree","Balanced BST","Tree of Trees","Nested Data Structures"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "就的是 in the first paragraph is read as a typo for 就是 (“is”)."
---

## Main Idea

In this problem $w$ is large, and we need two-dimensional sums. One workable approach is a nested data structure; the first idea is a Fenwick tree of dynamically allocated segment trees, with time complexity $O(log^2 m)$. But the space is still large: you can see that the segment trees take up a huge amount of space, so consider replacing them with balanced BSTs, which shrinks the space enormously while the time complexity stays the same.

For further optimization, consider hashing the indices.
