To solve the problem efficiently, we can use a combination of a monotonic stack and a Fenwick Tree (also known as a Binary Indexed Tree). Here's a step-by-step explanation followed by the complete C++ code implementation.
Step-by-Step Explanation:
-
Compute the Previous Greater Element (P[j]):
- For each building
j, we need to determine the last building to the left that is taller than j. This value is denoted as P[j].
- We can use a monotonic stack to keep track of the indices of buildings in decreasing order of their heights. This allows us to efficiently find
P[j] for each j.
-
Sort Buildings Based on P[j]:
- We create an array of pairs
(P[j], j) and sort them based on P[j] in ascending order. This sorting helps in efficiently processing the buildings while iterating through each i.
-
Use a Fenwick Tree to Count Valid j for Each i:
- We initialize a Fenwick Tree to keep track of the number of valid
j that can be paired with each i.
- Iterate through each
i from 1 to N. For each i, we add all j's to the Fenwick Tree where P[j] < i. Once these j's are in the tree, we query the number of j's that satisfy j > i.
-
Store and Output the Results:
- For each
i, store the count of valid j's in an array.
- Finally, print the results for all
i.
C++ Code Implementation:
#include <bits/stdc++.h>
using namespace std;
// Fenwick Tree (Binary Indexed Tree) for range sum queries and point updates
struct FenwickTree {
int size;
vector<int> tree;
FenwickTree(int n){
size = n;
tree.assign(n+1, 0);
}
// Add value 'val' at position 'idx'
void add(int idx, int val=1){
while(idx <= size){
tree[idx] += val;
idx += idx & (-idx);
}
}
// Query the prefix sum up to and including 'idx'
int query(int idx){
int res = 0;
while(idx >0){
res += tree[idx];
idx -= idx & (-idx);
}
return res;
}
// Query the range sum from 'l' to 'r'
int query(int l, int r){
if(l > r) return 0;
return query(r) - query(l-1);
}
};
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int N;
cin >> N;
vector<int> H(N+1);
for(int i=1;i<=N;i++) cin >> H[i];
// Compute P[j] using a stack
vector<int> P(N+1, 0);
stack<int> s;
for(int j=1;j<=N;j++){
while(!s.empty() && H[s.top()] <= H[j]){
s.pop();
}
if(!s.empty()){
P[j] = s.top();
}
else{
P[j] = 0;
}
s.push(j);
}
// Create a vector of pairs (P[j], j) and sort by P[j]
vector<pair<int, int>> sorted_j;
sorted_j.reserve(N);
for(int j=1;j<=N;j++) sorted_j.emplace_back(P[j], j);
sort(sorted_j.begin(), sorted_j.end(), [&](const pair<int,int> &a, const pair<int,int> &b) -> bool{
if(a.first != b.first) return a.first < b.first;
return a.second < b.second;
});
// Initialize Fenwick Tree
FenwickTree BIT(N);
// Iterate through i from 1 to N and compute answers
vector<int> ans(N+1, 0);
int idx =0;
for(int i=1;i<=N;i++){
// Add all j's with P[j] <i
while(idx < sorted_j.size() && sorted_j[idx].first <i){
BIT.add(sorted_j[idx].second, 1);
idx++;
}
// Query number of j's >i
if(i+1 <= N){
ans[i] = BIT.query(i+1, N);
}
else{
ans[i] =0;
}
}
// Output the answers
for(int i=1;i<=N;i++){
cout << ans[i] << " ";
}
return 0;
}
Explanation of the Code:
-
Fenwick Tree Implementation:
- The
FenwickTree structure provides methods to perform point updates and range sum queries efficiently in logarithmic time.
-
Reading Input:
- We read the number of buildings
N and their heights into the array H.
-
Computing P[j]:
- Using a stack, we compute
P[j] for each building j, which represents the index of the last building to the left of j that is taller than j.
-
Sorting Buildings:
- We create a
sorted_j vector containing pairs (P[j], j) and sort it based on P[j].
-
Processing Each i and Counting Valid j:
- For each
i, we add all valid j's to the Fenwick Tree where P[j] < i.
- We then query the number of
j's that are greater than i using the Fenwick Tree and store the result.
-
Output:
- Finally, we output the number of valid
j's for each i.
Complexity Analysis:
This solution efficiently handles the constraints given in the problem and provides the correct counts for each building i.