Untitled
unknown
plain_text
a year ago
3.2 kB
9
Indexable
#include <iostream>
#include <stack>
using namespace std;
// Potential function to track the number of elements in the stack
int potential(const stack<int>& s) {
return s.size();
}
int main() {
stack<int> a;
int input;
int current_potential = 0; // This will keep track of the current potential
while (true) {
cout << "Enter your choice: 1.push 2.pop 3.multipop 4.display 5.quit" << endl;
cin >> input;
switch (input) {
case 1: {
int val;
cout << "Enter value: ";
cin >> val;
a.push(val);
// Update potential function
int new_potential = potential(a);
int amortized_cost = 1 + (new_potential - current_potential);
current_potential = new_potential;
cout << "Amortized cost of push: " << amortized_cost << endl;
break;
}
case 2: {
if (a.empty()) {
cout << "Stack is empty." << endl;
} else {
a.pop();
// Update potential function
int new_potential = potential(a);
int amortized_cost = 1 + (new_potential - current_potential);
current_potential = new_potential;
cout << "Amortized cost of pop: " << amortized_cost << endl;
}
break;
}
case 3: {
int num_pops;
cout << "How many to multipop? ";
cin >> num_pops;
int actual_cost = 0;
while (num_pops > 0 && !a.empty()) {
a.pop();
num_pops--;
actual_cost++;
}
// Update potential function
int new_potential = potential(a);
int amortized_cost = actual_cost + (new_potential - current_potential);
current_potential = new_potential;
cout << "Amortized cost of multipop: " << amortized_cost << endl;
break;
}
case 4: {
// Display and empty the stack
int num_elements = a.size();
int actual_cost = 0;
while (!a.empty()) {
cout << a.top() << ' ';
a.pop();
actual_cost++;
}
cout << endl;
// Update potential function
int new_potential = potential(a);
int amortized_cost = actual_cost + (new_potential - current_potential);
current_potential = new_potential;
cout << "Amortized cost of display: " << amortized_cost << endl;
break;
}
case 5:
return 0;
default:
cout << "Invalid choice, please try again." << endl;
break;
}
}
return 0;
}
Editor is loading...
Leave a Comment