To solve this problem efficiently, especially given the large constraints (up to 500,000 queries), we need a strategic approach that avoids recalculating the entire grid after each ditch creation. Here's a comprehensive breakdown of the solution:
Problem Overview
-
Grid Representation: The agricultural land is a rectangle of size h × w. Ditches can be horizontal (H) or vertical (V), dividing the land into smaller rectangular plots.
-
Objective: After each ditch is created, partition the land such that:
- Adjacent plots have different crops (chessboard pattern).
- Maximize the total area assigned to shalgham (فضلغم).
Key Insights
-
Bipartition Nature: The chessboard pattern implies that the grid can be bipartitioned into two sets where no two adjacent plots are in the same set. Thus, the problem reduces to allocating areas to two sets while maximizing one.
-
Parity-Based Summation:
-
Dynamic Updates: After each ditch creation, horizontal or vertical, the parity of subsequent rows or columns may change, affecting the sums A, B, C, and D.
Data Structures and Algorithms
To efficiently handle dynamic updates and maintain the required sums, we can utilize Balanced Binary Search Trees (BBSTs) with augmented data. Specifically, we'll use Treaps with implicit keys to manage both rows and columns.
Treap Implementation Details
-
Node Structure:
val: Height of a row or width of a column.
sum_even: Sum of values at even indices in the subtree.
sum_odd: Sum of values at odd indices in the subtree.
size: Number of nodes in the subtree.
priority: Randomly assigned to maintain Treap properties.
flip: Lazy propagation flag to indicate if parity needs to be flipped in the subtree.
-
Core Operations:
- Split: Divides the Treap into two based on the index.
- Merge: Combines two Treaps into one.
- Insert: Adds a new node (row or column) at a specific position.
- Flip: Toggles the parity of nodes in a subtree, effectively swapping
sum_even and sum_odd.
-
Handling Insertions:
- When inserting a new ditch, determine where it fits in the sorted list of ditches.
- Split the Treap at the appropriate position to isolate the affected row or column.
- Insert the new smaller segments resulting from the split.
- Apply a flip operation to the right subtree to account for the change in parity due to the insertion.
Step-by-Step Solution
-
Initialize Treaps:
- Rows Treap: Start with a single row of height
h.
- Columns Treap: Start with a single column of width
w.
- Initialize
sum_even_rows = h, sum_odd_rows = 0, sum_even_cols = w, sum_odd_cols = 0.
-
Process Each Ditch Creation:
-
Calculate Shalgham Area:
Implementation
Below is the C++ implementation of the above approach using Treaps with implicit keys. Due to the complexity of implementing a Treap from scratch, detailed implementations of Treap operations are provided within the code.
#include <bits/stdc++.h>
using namespace std;
// Define the structure of a Treap node
struct TreapNode {
long long val; // Height or Width
long long sum_even;
long long sum_odd;
int size;
int priority;
bool flip;
TreapNode* left;
TreapNode* right;
TreapNode(long long _val) : val(_val), sum_even(0), sum_odd(0),
size(1), priority(rand()), flip(false), left(nullptr), right(nullptr) {}
};
// Update the size and sum_even, sum_odd of the node based on its children
void update(TreapNode* node) {
if (!node) return;
node->size = 1;
node->sum_even = 0;
node->sum_odd = 0;
if (node->left) {
node->size += node->left->size;
node->sum_even += node->left->sum_even;
node->sum_odd += node->left->sum_odd;
}
// Determine if current node is even or odd based on left subtree size
int index = node->left ? node->left->size : 0;
if (index % 2 == 0)
node->sum_even += node->val;
else
node->sum_odd += node->val;
if (node->right) {
node->size += node->right->size;
node->sum_even += node->right->sum_even;
node->sum_odd += node->right->sum_odd;
}
}
// Push down the flip operation to children
void push(TreapNode* node) {
if (node && node->flip) {
swap(node->sum_even, node->sum_odd);
if (node->left) node->left->flip ^= 1;
if (node->right) node->right->flip ^= 1;
node->flip = false;
}
}
// Split the treap into left (first 'k' nodes) and right (rest)
pair<TreapNode*, TreapNode*> split(TreapNode* node, int k) {
if (!node) return {nullptr, nullptr};
push(node);
int left_size = node->left ? node->left->size : 0;
if (k <= left_size) {
auto left_split = split(node->left, k);
node->left = left_split.second;
update(node);
return {left_split.first, node};
} else {
auto right_split = split(node->right, k - left_size - 1);
node->right = right_split.first;
update(node);
return {node, right_split.second};
}
}
// Merge two treaps
TreapNode* merge(TreapNode* left, TreapNode* right) {
if (!left || !right) return left ? left : right;
if (left->priority > right->priority) {
push(left);
left->right = merge(left->right, right);
update(left);
return left;
} else {
push(right);
right->left = merge(left, right->left);
update(right);
return right;
}
}
// Insert a node at position 'k'
TreapNode* insert(TreapNode* root, TreapNode* node, int k) {
auto splits = split(root, k);
return merge(merge(splits.first, node), splits.second);
}
// Function to get sum_even and sum_odd of the treap
pair<long long, long long> get_sum(TreapNode* root) {
if (!root) return {0, 0};
push(root);
return {root->sum_even, root->sum_odd};
}
// Function to find the position to insert the new cut
int find_position(vector<long long>& cuts, long long p) {
return upper_bound(cuts.begin(), cuts.end(), p) - cuts.begin() - 1;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
srand(time(0));
int w, h, q;
cin >> w >> h >> q;
// Initialize horizontal and vertical cuts
vector<long long> horizontal_cuts = {0, h};
vector<long long> vertical_cuts = {0, (long long)w};
// Initialize Treaps for rows and columns
TreapNode* rows = new TreapNode(h);
rows->sum_even = h;
rows->sum_odd = 0;
TreapNode* cols = new TreapNode(w);
cols->sum_even = w;
cols->sum_odd = 0;
for(int i = 0; i < q; ++i){
char t;
long long p;
cin >> t >> p;
if(t == 'H'){
// Insert horizontal cut
// Find where to insert
int pos = find_position(horizontal_cuts, p);
// Calculate heights
long long lower = horizontal_cuts[pos];
long long upper = horizontal_cuts[pos+1];
long long h1 = p - lower;
long long h2 = upper - p;
// Update cuts
horizontal_cuts.insert(horizontal_cuts.begin() + pos +1, p);
// Split the treap into left, middle, right
auto split1 = split(rows, pos);
auto split2 = split(split1.second, 1); // Split out the row to be split
// split2.first is the row to split
// Create two new rows
TreapNode* new_row1 = new TreapNode(h1);
TreapNode* new_row2 = new TreapNode(h2);
new_row1->sum_even = h1;
new_row1->sum_odd = 0;
new_row2->sum_even = h2;
new_row2->sum_odd = 0;
// Merge left + new_row1 + new_row2 + right
TreapNode* merged = merge(split1.first, new_row1);
merged = merge(merged, new_row2);
merged = merge(merged, split2.second);
// Now, all rows after pos+2 have their parity flipped
// To do this, split at pos+2 and flip the right part
auto final_split = split(merged, pos + 2);
if(final_split.second){
final_split.second->flip ^= 1;
}
// Merge back
rows = merge(final_split.first, final_split.second);
}
else{
// Insert vertical cut
// Find where to insert
int pos = find_position(vertical_cuts, p);
// Calculate widths
long long lower = vertical_cuts[pos];
long long upper = vertical_cuts[pos+1];
long long w1 = p - lower;
long long w2 = upper - p;
// Update cuts
vertical_cuts.insert(vertical_cuts.begin() + pos +1, p);
// Split the treap into left, middle, right
auto split1 = split(cols, pos);
auto split2 = split(split1.second, 1); // Split out the column to be split
// split2.first is the column to split
// Create two new columns
TreapNode* new_col1 = new TreapNode(w1);
TreapNode* new_col2 = new TreapNode(w2);
new_col1->sum_even = w1;
new_col1->sum_odd = 0;
new_col2->sum_even = w2;
new_col2->sum_odd = 0;
// Merge left + new_col1 + new_col2 + right
TreapNode* merged = merge(split1.first, new_col1);
merged = merge(merged, new_col2);
merged = merge(merged, split2.second);
// Now, all columns after pos+2 have their parity flipped
// To do this, split at pos+2 and flip the right part
auto final_split = split(merged, pos + 2);
if(final_split.second){
final_split.second->flip ^= 1;
}
// Merge back
cols = merge(final_split.first, final_split.second);
}
// Get sums
pair<long long, long long> row_sum = get_sum(rows);
pair<long long, long long> col_sum = get_sum(cols);
long long A = row_sum.first;
long long B = row_sum.second;
long long C = col_sum.first;
long long D = col_sum.second;
// Compute shalgham area
long long shalgham1 = A * C + B * D;
long long shalgham2 = A * D + B * C;
long long shalgham = max(shalgham1, shalgham2);
cout << shalgham << "\n";
}
}
Explanation of the Code
-
Initialization:
- Rows and Columns: Start with a single row and column, initializing their sums accordingly.
-
Processing Each Query:
- Insertion of Ditches:
- For a horizontal (
H p) or vertical (V p) ditch, determine where to insert the new cut based on its position.
- Split the existing row or column into two new segments.
- Update the Treap by inserting these new segments.
- Apply a flip operation to the right subtree to adjust for parity changes.
-
Updating Sums:
- After each insertion, retrieve the current sums of even and odd rows (
A and B) and columns (C and D).
-
Calculating Shalgham Area:
- Use the formula
max(A*C + B*D, A*D + B*C) to determine the maximum possible area that can be allocated to shalgham.
-
Output:
- After each query, output the computed shalgham area.
Complexity Analysis
-
Time Complexity:
- Each query involves a series of Treap operations (split, merge, insert, flip), each of which operates in
O(log N) time on average, where N is the number of rows or columns.
- Thus, for
q queries, the total time complexity is O(q log q).
-
Space Complexity:
- The Treaps store all rows and columns, leading to a space complexity of
O(q).
Conclusion
By leveraging balanced binary search trees (Treaps) with augmented data for managing parity-based sums, we can efficiently handle dynamic insertions and maintain the required sums to compute the maximum shalgham area after each ditch creation. This approach ensures that even with large inputs, the solution remains performant and accurate.