I need to speed up my algorithm. It is about finding the height of a tower. The tower is built from buckets. Each bucket has height and radius (1 <= height,radius <= 1000). Variable bucketCount
describe how many buckets are placed on tower (1 <= bucketCount
<= 10^6). We set buckets in sequence. Thickness of bucket is 0 (for simplicity)
Image of example tower:
I decided to use a stack. My algorithm for each bucket:
- If stack is empty, then push bucket to stack.
- If the bucket I hold is narrower then bucket on top then put it on the stack.
- Else while bucket I hold is wider: pop and find maximum height (for new bucket ground), after that push bucket which I hold.
For each bucket I added additional an variable ground
, which specifies the height at which the bucket is placed. Meantime I keep maximum height of tower in variable.
This task is automatically checked and gives output: time limit exceeded. I tried to optimize code but nothing gives positive result.
Example input: 2 20 20 30 30
Output: 50
#include <iostream>
#include <stack>
using namespace std;
struct Bucket{
public:
int height;
int radius;
int ground;
};
int main()
{
int ile;
cin >> ile;
for(int c = 0; c < ile; c++){
stack<Bucket> tower;
int hightestPoint = 0;
int bucketCount;
cin >> bucketCount;
Bucket temp;
Bucket temporary; //Used to speed up a bit
int maksimum;
int sum;
int counter = 0; //Its size of the Stack. Used it because thought its faster then empty() function
for(int i = 0; i < bucketCount; i++){
cin >> temp.radius >> temp.height;
maksimum = -1;
sum = 0;
if(counter == 0){
temp.ground = 0;
tower.push(temp);
counter++;
} else {
if(temp.radius < tower.top().radius){ //If bucket is narrower then push it
temp.ground = tower.top().ground;
tower.push(temp);
counter++;
} else { //If bucket is wider
while((counter > 0) && temp.radius >= (temporary = tower.top()).radius){ //Pop and search for new ground (maximum)
sum = temporary.height + temporary.ground;
if(maksimum < sum){
maksimum = sum;
}
tower.pop();
counter--;
}
temp.ground = maksimum; //Set ground for new bucket
tower.push(temp);
counter++;
}
}
sum = temp.height + temp.ground; //Meantime find highest point in stack
if(hightestPoint < sum){
hightestPoint = sum;
}
}
cout << hightestPoint << endl;
}
return 0;
}