Why I am getting TLE at CSES problem "Book Shop" of dynamic programming - c++17

TLE
I am getting the same error in case of coin combination 2
link to the problem
Failed tc
//*******************************************
// Code by:
// * *
// * * * *
// ***** *****
// * * * *
// * *arushi * * garwal
//*******************************************
#include <bits/stdc++.h>
using namespace std;
#define fastio() \
ios_base::sync_with_stdio(false); \
cin.tie(NULL);
#define yes cout << "YES\n"
#define no cout << "NO\n"
#define MOD 1000000007
#define endl "\n"
#define MOD1 998244353
#define INF 1e18
#define nline "\n"
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define ff first
#define ss second
#define PI 3.141592653589793238462
#define set_bits __builtin_popcountll
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define for0 for (i = 0; i < n; i++)
#define for1 for (i = 1; i <= n; i++)
#define forr for (i = n - 1; i >= 0; i--)
typedef long long ll;
typedef unsigned long long ull;
typedef long double lld;
// typedef tree<pair<int, int>, null_type, less<pair<int, int>>, rb_tree_tag, tree_order_statistics_node_update > pbds; // find_by_order, order_of_key
#ifndef ONLINE_JUDGE
#define debug(x) \
cerr << #x << " "; \
_print(x); \
cerr << endl;
#else
#define debug(x)
#endif
void _print(ll t)
{
cerr << t;
}
void _print(int t) { cerr << t; }
void _print(string t) { cerr << t; }
void _print(char t) { cerr << t; }
void _print(lld t) { cerr << t; }
void _print(double t) { cerr << t; }
void _print(ull t) { cerr << t; }
template <class T, class V>
void _print(pair<T, V> p);
template <class T>
void _print(vector<T> v);
template <class T>
void _print(set<T> v);
template <class T, class V>
void _print(map<T, V> v);
template <class T>
void _print(multiset<T> v);
template <class T, class V>
void _print(pair<T, V> p)
{
cerr << "{";
_print(p.ff);
cerr << ",";
_print(p.ss);
cerr << "}";
}
template <class T>
void _print(vector<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(set<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T>
void _print(multiset<T> v)
{
cerr << "[ ";
for (T i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
template <class T, class V>
void _print(map<T, V> v)
{
cerr << "[ ";
for (auto i : v)
{
_print(i);
cerr << " ";
}
cerr << "]";
}
// EVERY SINGLE QUES TAKES YOU TOWARDS YOUR GOAL :)
// ********************************************************
int i, t, j, sum, n, ans, k;
const int M = 1e9 + 7;
const int N = 1e5;
int dp[1001][N + 1];
ll binExp(ll a, ll b)
{
ll result = 1;
while (b > 0)
{
if (b & 1)
result = (result * a) % M;
a = (a * a) % M;
b >>= 1;
}
return result;
}
int fun(int i, int price[], int pages[], int cost)
{
if (i < 0)
return 0;
if (cost == 0)
return 0;
if (dp[i][cost] != -1)
return dp[i][cost];
int ans = fun(i - 1, price, pages, cost);
if (cost >= price[i])
ans = max(ans, fun(i - 1, price, pages, cost - price[i]) + pages[i]);
return dp[i][cost] = ans;
}
void hacked()
{
// cin>>n;
// string s;
// cin>>s;
cin >> n >> sum;
int price[n];
int pages[n];
memset(dp, -1, sizeof(dp));
for (i = 0; i < n; i++)
{
cin >> price[i];
}
for (i = 0; i < n; i++)
{
cin >> pages[i];
}
cout << fun(n - 1, price, pages, sum) << endl;
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("Error.txt", "w", stderr);
#endif
ios_base::sync_with_stdio(false);
cin.tie(NULL);
hacked();
return 0;
}`
I tried using int instead of long long but still getting tle.
You are in a book shop which sells n different books. You know the
price and number of pages of each book.
You have decided that the total price of your purchases will be at
most x. What is the maximum number of pages you can buy? You can buy
each book at most once.

Maybe because of the auxiliary space used up by top-down approach - the recursive stack- bottom-up works tho.
UPD: I just read this CF BLOG, people mention about the strict constraints of CSES, so it's better to solve using bottom-up.

Related

I am trying to have stable flight with px4 and ros2 offboard control

Hello guys I have a offboard code which give about 50 setpoints to drone. It draws spiral with that setpoints. My problem is I couldnt get smooth travel. In every setpoint drone gives a high roll or pitch instant and then floats to the next setpoint. Is there a way to have stable velocity while passing the setpoints. Here is the code:
#include <px4_msgs/msg/offboard_control_mode.hpp>
#include <px4_msgs/msg/trajectory_setpoint.hpp>
#include <px4_msgs/msg/timesync.hpp>
#include <px4_msgs/msg/vehicle_command.hpp>
#include <px4_msgs/msg/vehicle_control_mode.hpp>
#include <px4_msgs/msg/vehicle_local_position.hpp>
#include <rclcpp/rclcpp.hpp>
#include <stdint.h>
#include <chrono>
#include <iostream>
#include "std_msgs/msg/string.hpp"
#include <math.h>
float X;
float Y;
using namespace std::chrono;
using namespace std::chrono_literals;
using namespace px4_msgs::msg;
class setpoint : public rclcpp::Node {
public:
setpoint() : Node("setpoint") {
offboard_control_mode_publisher_ =
this->create_publisher<OffboardControlMode>("fmu/offboard_control_mode/in", 10);
trajectory_setpoint_publisher_ =
this->create_publisher<TrajectorySetpoint>("fmu/trajectory_setpoint/in", 10);
vehicle_command_publisher_ =
this->create_publisher<VehicleCommand>("fmu/vehicle_command/in", 10);
// get common timestamp
timesync_sub_ =
this->create_subscription<px4_msgs::msg::Timesync>("fmu/timesync/out", 10,
[this](const px4_msgs::msg::Timesync::UniquePtr msg) {
timestamp_.store(msg->timestamp);
});
offboard_setpoint_counter_ = 0;
auto sendCommands = [this]() -> void {
if (offboard_setpoint_counter_ == 10) {
// Change to Offboard mode after 10 setpoints
this->publish_vehicle_command(VehicleCommand::VEHICLE_CMD_DO_SET_MODE, 1, 6);
// Arm the vehicle
this->arm();
}
//-------------
subscription_ = this->create_subscription<px4_msgs::msg::VehicleLocalPosition>(
"/fmu/vehicle_local_position/out",
#ifdef ROS_DEFAULT_API
10,
#endif
[this](const px4_msgs::msg::VehicleLocalPosition::UniquePtr msg) {
X = msg->x;
Y = msg->y;
std::cout << "\n\n\n\n\n\n\n\n\n\n";
std::cout << "RECEIVED VEHICLE GPS POSITION DATA" << std::endl;
std::cout << "==================================" << std::endl;
std::cout << "ts: " << msg->timestamp << std::endl;
//std::cout << "lat: " << msg->x << std::endl;
//std::cout << "lon: " << msg->y << std::endl;
std::cout << "lat: " << X << std::endl;
std::cout << "lon: " << Y << std::endl;
std::cout << "waypoint: " << waypoints[waypointIndex][0] << std::endl;
std::cout << "waypoint: " << waypoints[waypointIndex][1] << std::endl;
if((waypoints[waypointIndex][0] + 0.3 > X && waypoints[waypointIndex][0] - 0.3 < X)&&(waypoints[waypointIndex][1] + 0.3 > Y && waypoints[waypointIndex][1] - 0.3 < Y)){
waypointIndex++;
if (waypointIndex >= waypoints.size())
exit(0);
//waypointIndex = 0;
RCLCPP_INFO(this->get_logger(), "Next waypoint: %.2f %.2f %.2f", waypoints[waypointIndex][0], waypoints[waypointIndex][1], waypoints[waypointIndex][2]);
}
});
//--------------
// offboard_control_mode needs to be paired with trajectory_setpoint
publish_offboard_control_mode();
publish_trajectory_setpoint();
// stop the counter after reaching 11
if (offboard_setpoint_counter_ < 11) {
offboard_setpoint_counter_++;
}
};
/*
auto nextWaypoint = [this]() -> void {
waypointIndex++;
if (waypointIndex >= waypoints.size())
waypointIndex = 0;
RCLCPP_INFO(this->get_logger(), "Next waypoint: %.2f %.2f %.2f", waypoints[waypointIndex][0], waypoints[waypointIndex][1], waypoints[waypointIndex][2]);
};
*/
commandTimer = this->create_wall_timer(100ms, sendCommands);
//waypointTimer = this->create_wall_timer(2s, nextWaypoint); //EA
}
void arm() const;
void disarm() const;
void topic_callback() const;
private:
std::vector<std::vector<float>> waypoints = {{0,0,-5,},
{2,0,-5,},
{2.35216,0.476806,-5,},
{2.57897,1.09037,-5,},
{2.64107,1.80686,-5,},
{2.50814,2.58248,-5,},
{2.16121,3.36588,-5,},
{1.59437,4.10097,-5,},
{0.815842,4.73016,-5,},
{-0.151838,5.19778,-5,},
{-1.27233,5.45355,-5,},
{-2.49688,5.45578,-5,},
{-3.76641,5.17438,-5,},
{-5.01428,4.59315,-5,},
{-6.1696,3.71161,-5,},
{-7.16089,2.54591,-5,},
{-7.91994,1.12896,-5,},
{-8.38568,-0.490343,-5,},
{-8.50782,-2.24876,-5,},
{-8.25018,-4.07119,-5,},
{-7.59329,-5.87384,-5,},
{-6.53644,-7.56803,-5,},
{-5.09871,-9.06439,-5,},
{-3.31919,-10.2773,-5,},
{-1.25611,-11.1293,-5,},
{1.01499,-11.5555,-5,},
{3.40395,-11.5071,-5,},
{5.8096,-10.9548,-5,},
{8.12407,-9.89139,-5,},
{10.2375,-8.33272,-5,},
{12.0431,-6.31859,-5,},
{13.4424,-3.91182,-5,},
{14.3502,-1.19649,-5,},
{14.6991,1.72493,-5,},
{14.4435,4.73543,-5,},
{13.5626,7.70817,-5,},
{12.0624,10.5118,-5,},
{9.97696,13.0162,-5,},
{7.36759,15.0983,-5,},
{4.32167,16.6482,-5,},
{0.949612,17.5744,-5,},
{-2.619,17.8084,-5,},
{-6.24045,17.3094,-5,},
{-9.76262,16.0665,-5,},
{-13.0314,14.1004,-5,},
{-15.8974,11.4644,-5,},
{-18.2226,8.24237,-5,},
{-19.8868,4.54696,-5,},
{-20.7936,0.515337,-5,},
{-20.8754,-3.69574,-5,},
{-20.0972,-7.91595,-5,},
{-20.8754,-3.69574,-5,},
{-20.7936,0.515337,-5,},
{-19.8868,4.54696,-5,},
{-18.2226,8.24237,-5,},
{-15.8974,11.4644,-5,},
{-13.0314,14.1004,-5,},
{-9.76262,16.0665,-5,},
{-6.24045,17.3094,-5,},
{-2.619,17.8084,-5,},
{0.949612,17.5744,-5,},
{4.32167,16.6482,-5,},
{7.36759,15.0983,-5,},
{9.97696,13.0162,-5,},
{12.0624,10.5118,-5,},
{13.5626,7.70817,-5,},
{14.4435,4.73543,-5,},
{14.6991,1.72493,-5,},
{14.3502,-1.19649,-5,},
{13.4424,-3.91182,-5,},
{12.0431,-6.31859,-5,},
{10.2375,-8.33272,-5,},
{8.12407,-9.89139,-5,},
{5.8096,-10.9548,-5,},
{3.40395,-11.5071,-5,},
{1.01499,-11.5555,-5,},
{-1.25611,-11.1293,-5,},
{-3.31919,-10.2773,-5,},
{-5.09871,-9.06439,-5,},
{-6.53644,-7.56803,-5,},
{-7.59329,-5.87384,-5,},
{-8.25018,-4.07119,-5,},
{-8.50782,-2.24876,-5,},
{-8.38568,-0.490343,-5,},
{-7.91994,1.12896,-5,},
{-7.16089,2.54591,-5,},
{-6.1696,3.71161,-5,},
{-5.01428,4.59315,-5,},
{-3.76641,5.17438,-5,},
{-2.49688,5.45578,-5,},
{-1.27233,5.45355,-5,},
{-0.151838,5.19778,-5,},
{0.815842,4.73016,-5,},
{1.59437,4.10097,-5,},
{2.16121,3.36588,-5,},
{2.50814,2.58248,-5,},
{2.64107,1.80686,-5,},
{2.57897,1.09037,-5,},
{2.35216,0.476806,-5,},
{2,0,-5,},
{0,0,-5,},
{0,0,0,}
}; // Land
int waypointIndex = 0;
rclcpp::TimerBase::SharedPtr commandTimer;
rclcpp::TimerBase::SharedPtr waypointTimer;
rclcpp::Publisher<OffboardControlMode>::SharedPtr offboard_control_mode_publisher_;
rclcpp::Publisher<TrajectorySetpoint>::SharedPtr trajectory_setpoint_publisher_;
rclcpp::Publisher<VehicleCommand>::SharedPtr vehicle_command_publisher_;
rclcpp::Subscription<px4_msgs::msg::Timesync>::SharedPtr timesync_sub_;
//
rclcpp::Subscription<px4_msgs::msg::VehicleLocalPosition>::SharedPtr subscription_;
//
std::atomic<uint64_t> timestamp_; //!< common synced timestamped
uint64_t offboard_setpoint_counter_; //!< counter for the number of setpoints sent
void publish_offboard_control_mode() const;
void publish_trajectory_setpoint() const;
void publish_vehicle_command(uint16_t command, float param1 = 0.0,
float param2 = 0.0) const;
};
void setpoint::arm() const {
publish_vehicle_command(VehicleCommand::VEHICLE_CMD_COMPONENT_ARM_DISARM, 1.0);
RCLCPP_INFO(this->get_logger(), "Arm command send");
}
void setpoint::disarm() const {
publish_vehicle_command(VehicleCommand::VEHICLE_CMD_COMPONENT_ARM_DISARM, 0.0);
RCLCPP_INFO(this->get_logger(), "Disarm command send");
}
void setpoint::publish_offboard_control_mode() const {
OffboardControlMode msg{};
msg.timestamp = timestamp_.load();
msg.position = true;
msg.velocity = false;
msg.acceleration = false;
msg.attitude = false;
msg.body_rate = false;
offboard_control_mode_publisher_->publish(msg);
}
void setpoint::publish_trajectory_setpoint() const {
TrajectorySetpoint msg{};
msg.timestamp = timestamp_.load();
msg.position = {waypoints[waypointIndex][0],waypoints[waypointIndex][1],waypoints[waypointIndex][2]};
msg.yaw = std::nanf("0"); //-3.14; // [-PI:PI]
trajectory_setpoint_publisher_->publish(msg);
}
void setpoint::publish_vehicle_command(uint16_t command, float param1,
float param2) const {
VehicleCommand msg{};
msg.timestamp = timestamp_.load();
msg.param1 = param1;
msg.param2 = param2;
msg.command = command;
msg.target_system = 1;
msg.target_component = 1;
msg.source_system = 1;
msg.source_component = 1;
msg.from_external = true;
vehicle_command_publisher_->publish(msg);
}
int main(int argc, char* argv[]) {
std::cout << "Starting setpoint node..." << std::endl;
setvbuf(stdout, NULL, _IONBF, BUFSIZ);
rclcpp::init(argc, argv);
rclcpp::spin(std::make_shared<setpoint>());
rclcpp::shutdown();
return 0;
}
We send the setpoints to the controller by giving reference points. The aircraft will then try to maneuver to the given points via its control strategy (usually PID). Therefore, to have a smooth maneuver, it is usually suggested to give a series of discrete points between two waypoints, i.e., trajectory which parameterized by time. It should then solve the abrupt motion of your UAV. I'm no expert, but I hope this helps.

reading doubly linked list n position

My doubly linked list contains abc...z. which was read from first file..
My second file contains int 4,10,8,-3.
based on my second file I am suppose do display abc..z on the screen..
4 -> I am going forward till D then 10 -> more till N, then so on..
How can I do that? please any help..
anyhlep would be really appriciated..
#include <iostream>
#include <fstream>
using namespace std;
class Myclass{
public:
void putItem(char cha);
void printItme();
void getIndex(int);
Myclass();
private:
struct Node
{
char aplBat;
Node *next;
Node *prev;
};
Node *head;
int potionIndex = 0;
};
int main(){
ifstream inputFile, inputInt;
Myclass obj;
string stringInt;
double valData = 0;
int total = 0;
char charData;
/*my first file with alpa */
inputFile.open("Letters.txt");
if(inputFile.good())
{
while(inputFile >> charData)
{
obj.putItem(charData);
}
}
else
cout << "Error " << endl;
inputFile.close();
//From right here.. I am reading data from file Sequence, 3,5,-2,10,-5
inputInt.open("Sequence.txt");
if(inputInt.good())
{
while(getline(inputInt, stringInt, ',')){
valData = atof(stringInt.c_str());
total += valData;
obj.getIndex(total);
}
//cout << "Total " << total << endl;
cout << "FIle ok " << endl;
obj.printItme();
}
else
cout << "Error " << endl;
inputInt.close();
cout << endl;
return 0;
}
void Myclass::putItem(char cha){
Node *newNode;
newNode = new Node;
newNode->aplBat = cha;
newNode->prev = nullptr;
newNode->next = nullptr;
if(!head)
{
head = newNode;
}
else
{
head->prev = newNode;
newNode->next = head;
head = newNode;
}
}
void Myclass::printItme()
{
Node *temp = head;
if(temp == nullptr)
{
cout << "Empty List " << endl;
}
while(temp->next != nullptr)
{
temp = temp->next;
}
while(temp->prev != nullptr)
{
cout << temp->aplBat << " ";
temp = temp->prev;
}
cout << "Repitation " << potionIndex << endl;
}
Myclass::Myclass()
{
head = nullptr;
}
void Myclass::getIndex(int val)
{
potionIndex = val;
}

Possible bug in libc++ for mac os ,string destructor is not called when string obj goes out of scope

In libc++ i have found that basic_string destructor does not gets called , once string goes out of the scope the memory is freed by calling delete operator rather than calling its destructor and then calling the delete operator from destructor, why so?
Can some one explain this?
see the sample program
void * operator new ( size_t len ) throw ( std::bad_alloc )
{
void * mem = malloc( len );
if ( (mem == 0) && (len != 0) )
throw std::bad_alloc();
return mem;
}
void operator delete ( void * ptr ) throw()
{
if ( ptr != 0 )
free( ptr );
}
int main(int argc, const char * argv[])
{
std::string mystr("testing very very very big string for string class");
std::string mystr2(mystr1.begin(),mystr.end());
}
Put break point on new and delete and then check the call stack.
new operator gets called from basic_string class while the delete gets called from the end of main, while ideally basic_string destructor should have called first and then the delete operator should be called via deallocate call of allocator, this is valid for 2nd string creation.
I'm seeing the same thing in the debugger that you are; I don't know for sure, but I suspect that stuff is getting inlined. The destructor for basic_string is very small; a single test (for the small string optimization), and then a call to the allocator's deallocate function (through allocate_traits). std::allocators allocate function is also quite small, just a wrapper around operator delete.
You could test this by writing your own allocator. (Later: see below)
More stuff that I generated while investigating this question; read on if you're interested.
[Note: there's a bug in your code - in the second line you wrote: mystr1.begin(),mystr.end()) - where is mystr1 declared?]
Assuming that's a typo, I tried some slightly different code:
#include <string>
#include <new>
#include <iostream>
int news = 0;
int dels = 0;
void * operator new ( size_t len ) throw ( std::bad_alloc )
{
void * mem = malloc( len );
if ( (mem == 0) && (len != 0) )
throw std::bad_alloc();
++news;
return mem;
}
void operator delete ( void * ptr ) throw()
{
++dels;
if ( ptr != 0 )
free( ptr );
}
int main(int argc, const char * argv[])
{
{
std::string mystr("testing very very very big string for string class");
std::string mystr2(mystr.begin(),mystr.end());
std::cout << "News = " << news << "; Dels = " << dels << std::endl;
}
std::cout << "News = " << news << "; Dels = " << dels << std::endl;
}
If you run this code, it prints (at least for me):
News = 2; Dels = 0
News = 2; Dels = 2
which is exactly what it should.
If I toss the code into compiler explorer, then I see both the calls to basic_string::~basic_string(), exactly as I expect. (Well, I see three of them, but one of them is in an exception handling block, which ends with a call to _Unwind_resume).
Later - this code:
#include <string>
#include <new>
#include <iostream>
int news = 0;
int dels = 0;
template <class T>
class MyAllocator
{
public:
typedef T value_type;
MyAllocator() noexcept {}
template <class U>
MyAllocator(MyAllocator<U>) noexcept {}
T* allocate(std::size_t n)
{
++news;
return static_cast<T*>(::operator new(n*sizeof(T)));
}
void deallocate(T* p, std::size_t)
{
++dels;
return ::operator delete(static_cast<void*>(p));
}
friend bool operator==(MyAllocator, MyAllocator) {return true;}
friend bool operator!=(MyAllocator, MyAllocator) {return false;}
};
int main(int argc, const char * argv[])
{
{
typedef std::basic_string<char, std::char_traits<char>, MyAllocator<char>> S;
S mystr("testing very very very big string for string class");
S mystr2(mystr.begin(),mystr.end());
std::cout << "Allocator News = " << news << "; Allocator Dels = " << dels << std::endl;
}
std::cout << "Allocator News = " << news << "; Allocator Dels = " << dels << std::endl;
}
prints:
Allocator News = 2; Allocator Dels = 0
Allocator News = 2; Allocator Dels = 2
which confirms that the allocator is getting called.

(HW) Pallindrom using Stack and Queue, Run Time Error

Alright, i have a hw assignment to check if an inserted string is a palindrome. The string must first be inserted into a stack, a queue, and then compared. I have the program up and running, for me that is. My teacher, when trying to grade it experience(d) a run time error. Also, getline portable is a requirement of the assignment and came with the file and instructions.
This is the note from the teacher:
Check if a line is a palindrome. Ignore spaces? y/n y (her running the code)
Input line to check
(where she gets the runtime error)
175 [main] csc240Summer2014PE8Student 10060 open_stackdumpfile: Dumping stack trace to csc240Summer2014PE8Student.exe.stackdump
#include <iostream>
#include <stack>
#include <queue>
#include <string>
using namespace std;
istream& getline_portable( istream& is, string& str ) {
istream& ris = std::getline(is,str);
if ( str.size() && str[str.size()-1] == '\r' )
str.resize(str.size()-1);
return ris;
}
int main()
{
stack<char> s;
queue<char> q;
char c, choice, b;
string str;
int i = 0;
int count = 0;
do
{
cout<<"Check if a line is a palindrome. Ignore spaces? y/n ";
cin >> b;
cin.ignore();
tolower(b);
cout<<"Input line to check\n";
getline_portable(cin,str);
for(int j = 0; j < str.size(); j++)
str[j] = tolower(str[j]);
if(b == 'n')
{
for(int j = 0; j < str.size(); j++)
{
c = str[j];
q.push(c);
s.push(c);
}
}
else if (b == 'y')
{
for(int j = 0; j < str.size() - count; j++)
{
c = str[j];
if(isspace(c))
{
}
else if(!isspace(c))
{
q.push(c);
s.push(c);
}
}
}
do
{
if(q.front() != s.top())
{
i = false;
break;
}
else
{
i = true;
s.pop();
q.pop();
}
}while(!q.empty() && !s.empty());
if (i == true)
cout << str << " is a pallindrom.\n";
else if (i == false)
cout << "Your input of " << str << " is not a pallindrome.\n";
cout << "Would you like to test another string? y/n ";
cin >> choice;
tolower(choice);
cin.ignore();
}while (choice == 'y');
cout << "Press enter to continue...";
cin.get();
return 0;
}

Is there a way to get my program to convert characters to integers?

I have been running this and typing "12+" as the expression. 'm down to trying to add the top value and next value and it keeps giving me the result 'c' but I want the result to be 3. So is there any way to get my program to convert char 'c' to int '3' and char 'd' to int 4 and so on ?
//array based stack implementation
class Stack
{
private:
int capacity; //max size of stack
int top; //index for top element
char *listArray; //array holding stack elements
public:
Stack (int size = 50){ //constructor
capacity = size;
top = 0;
listArray = new char[size];
}
~Stack() { delete [] listArray; } //destructor
void push(char it) { //Put "it" on stack
listArray[top++] = it;
}
char pop() { //pop top element
return listArray [--top];
}
char& topValue() const { //return top element
return listArray[top-1];
}
char& nextValue() const {//return second to top element
return listArray[top-2];
}
int length() const { return top; } //return length
};
int main()
{
string exp;
char it = ' ';
int count;
int push_length;
cout << "Enter an expression in postfix notation:\n";
cin >> exp;
cout << "The number of characters in your expression is " << exp.length() << ".\n";
Stack STK;
for(count= 0; count < exp.length() ;count++)
{
if (exp[count] == '+')
{
it = exp[count - 1];
cout << it << "?\n";
while (!isdigit(it))
{
cout << it << "!\n";
it = exp[count--];
}
STK.push(it);
cout << STK.topValue() << "\n";
it = exp[count - 2];
cout << it << "\n";
if (isdigit(it))
{
STK.push(it);
}
cout << STK.topValue() << "\n";
cout << STK.nextValue() << "\n";
it = STK.topValue() + STK.nextValue();
cout << it << "\n";
STK.pop();
STK.pop();
STK.push(it);
cout << STK.topValue() << "\n";
}
}
cout << "The number of characters pushed into the stack is " << STK.length() << ".\n";
push_length = STK.length();
return(0);
}
You could do something like this:
char ch='d'; //ch is the character to convert
int i=1+(ch-'a');

Resources