-
Notifications
You must be signed in to change notification settings - Fork 13
/
rational-number-tree.cpp
151 lines (122 loc) · 3.07 KB
/
rational-number-tree.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
/*------------ Defines -----------*/
#define DEBUG 0
/*------- Types definition -------*/
typedef long long LONG;
static void Dbg(const string& msg) { if ( DEBUG ) { cerr << msg << endl; } }
struct Rational
{
LONG x, y;
Rational(LONG px=1, LONG py=1):
x(px), y(py)
{}
Rational(string& s)
{
auto pos = s.find('/');
if ( pos != string::npos )
{
x = stoll(s, &pos , 0);
s = s.substr(pos+1);
y = stoll(s, &pos, 0);
Rational::simplify(this);
Dbg("String in the form a/q");
printDbg();
toDirections();
}
else
{
x = 1;
y = 1;
Rational Pl(0,1), Pr(1,0);
// TODO - convertir à la volée
for( const auto& c : s )
{
if ( c == 'R' )
{
Pl = *this;
*this += Pr;
}
else
{
Pr = *this;
*this += Pl;
}
Rational::simplify(this);
}
toString();
}
}
Rational& operator=(const Rational& r)
{
x = r.x;
y = r.y;
return *this;
}
Rational& operator+=(const Rational& r)
{
x += r.x;
y += r.y;
return *this;
}
bool operator==(const Rational& r)
{
return (r.x == x && r.y == y);
}
bool operator!=(const Rational& r)
{
return !(*this == r);
}
bool operator>(const Rational& r)
{
LONG l_y1 = (y == 0) ? 1 : y ;
LONG l_y2 = (r.y == 0) ? 1 : r.y;
return ( static_cast<double>(x)/l_y1 > static_cast<double>(r.x)/l_y2 );
}
static void simplify(Rational* r)
{
if ( r == nullptr ) { return; }
auto d = __gcd(r->x, r->y);
r->x /= d;
r->y /= d;
}
void printDbg(void) const { if ( DEBUG ) { cerr << x << "/" << y << endl; } }
void toString(void) const { cout << x << "/" << y << endl; }
void toDirections(void)
{
string res = "";
Rational Pl(0,1), Pr(1,0), Pc(1,1);
while ( *this != Pc )
{
if ( *this > Pc )
{
Pl = Pc;
Pc += Pr;
res += "R";
}
else
{
Pr = Pc;
Pc += Pl;
res += "L";
}
Rational::simplify(&Pc);
}
cout << res << endl;
}
};
int main()
{
string line;
int tests;
cin >> tests; cin.ignore();
for (int i = 0; i < tests; i++)
{
getline(cin, line);
Rational r(line);
}
}