-
Notifications
You must be signed in to change notification settings - Fork 0
/
exam.cpp
121 lines (108 loc) · 2.42 KB
/
exam.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
115
116
117
118
119
120
121
//
// main.cpp
// P&D: EXAM 08.06.22
//
// Created by Julia Vister on 08/06/2022.
// The task is to write a function fun, which takes two integers n and m as arguments. The function calculates and returns an integer.
#include <iostream>
#include <stdexcept>
#include <stack>
struct nm {
int n;
int m;
};
class Stack{
int elements;
int capacity;
nm *mem;
public:
Stack():
capacity(10),
mem(new nm[capacity]),
elements(0)
{}
bool empty(){
return elements==0;
}
void push(int x, int y){ //push the pair n,m on the stack
if(capacity==elements)
{
nm *tmp = new nm[capacity *2];
for(int i=0;i<capacity;i++)
{
tmp[i]=mem[i];
}
delete [] mem;
mem = tmp;
capacity *= 2;
}
nm a;
a.n=x;
a.m=y;
mem[elements] = a;
elements ++;
}
nm top(){ //returns topmost pair
if(empty())
{
throw std::runtime_error("Cannot return value from empty stack!");
}
return mem[elements -1];
}
void pop(){ //removes pair
if(empty())
{
throw std::runtime_error("Cannot remove value from empty stack!");
}
elements--;
}
~Stack() {
delete[]mem;
}
int fun(int n, int m)
{
int sum=0;
push(n, m);
while(!empty()){
nm T = top();
pop();
int x=T.n;
int y=T.m;
if(x==0 || y==0)
{
sum=sum+1;
}
else{
push(x-1, y);
push(x, y-1);
}
}
return sum;
}
Stack &operator=(Stack cpy){
capacity=cpy.capacity;
elements=cpy.elements;
std::swap(mem, cpy.mem);
return *this;
}
Stack(const Stack& original):
capacity(original.capacity),
elements(original.elements),
mem(new nm[capacity])
{
for(int i=0;i<elements;i++){
mem[i]=original.mem[i];
}
}
};
int main() {
Stack S;
Stack T;
std::cout << "Test: it runs!";
std::cout << S.fun(0,0) << std::endl;
std::cout << T.fun(1,1) << std::endl;
std::cout << T.fun(3,4) << std::endl;
std::cout << T.fun(2,6) << std::endl;
std::cout << S.fun(12,14) << std::endl;
return 0;
}