-
Notifications
You must be signed in to change notification settings - Fork 0
/
3.2.cpp
114 lines (104 loc) · 1.9 KB
/
3.2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
using namespace std;
const int MAX_INT = ~(1<<31);//2147483647
typedef struct node{
int val, min;
}node;
class StackWithMin{
public:
StackWithMin(int size=1000){
buf = new node[size];
buf[0].min = MAX_INT;
cur = 0;
}
~StackWithMin(){
delete[] buf;
}
void push(int val){
buf[++cur].val = val;
if(val<buf[cur-1].min) buf[cur].min = val;
else buf[cur].min = buf[cur-1].min;
}
void pop(){
--cur;
}
int top(){
return buf[cur].val;
}
bool empty(){
return cur==0;
}
int min(){
return buf[cur].min;
}
private:
node *buf;
int cur;
};
class stack{
public:
stack(int size=1000){
buf = new int[size];
cur = -1;
}
~stack(){
delete[] buf;
}
void push(int val){
buf[++cur] = val;
}
void pop(){
--cur;
}
int top(){
return buf[cur];
}
bool empty(){
return cur==-1;
}
private:
int *buf;
int cur;
};
class StackWithMin1{
public:
StackWithMin1(){
}
~StackWithMin1(){
}
void push(int val){
s1.push(val);
if(val<=min())
s2.push(val);
}
void pop(){
if(s1.top()==min())
s2.pop();
s1.pop();
}
int top(){
return s1.top();
}
bool empty(){
return s1.empty();
}
int min(){
if(s2.empty()) return MAX_INT;
else return s2.top();
}
private:
stack s1, s2;
};
int main(){
//cout<<MIN_INT<<endl;
StackWithMin1 mystack;
for(int i=0; i<20; ++i)
mystack.push(i);
cout<<mystack.min()<<" "<<mystack.top()<<endl;
mystack.push(-100);
mystack.push(-100);
cout<<mystack.min()<<" "<<mystack.top()<<endl;
mystack.pop();
cout<<mystack.min()<<" "<<mystack.top()<<endl;
return 0;
}