-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP442.cpp
72 lines (65 loc) · 1.76 KB
/
P442.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
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <string>
typedef std::string String;
typedef std::pair<int,int> NM;
typedef std::pair<NM,int> MatrixInfo; // matrix, multiplications.
String readLine() {
char w[309];
gets(w);
return String(w);
}
int die() {
int *a = NULL;
a[42] = 666;
return 0;
}
MatrixInfo parse(const String &s, int &sI, NM const * const matrices) {
char c = s[sI++];
if(c != '(')
return MatrixInfo(matrices[c-'A'], matrices[c-'A'].first < 0 ? die() : 0);
MatrixInfo left = parse(s, sI, matrices);
if(left.second < 0) {
//std::cerr << "Left error!" << std::endl;
return left;
}
MatrixInfo right = parse(s, sI, matrices);
if(right.second < 0) {
//std::cerr << "Right error!" << std::endl;
return right;
}
if(left.first.second != right.first.first) {
//std::cerr << "Error: " << left.first.second << "!=" << right.first.first << std::endl;
return MatrixInfo(NM(0,0),-1);
}
int cnt = left.second + right.second + left.first.first*left.first.second*right.first.second;
MatrixInfo ret(NM(left.first.first, right.first.second), cnt);
++sI; // ')'
return ret;
}
int main() {
int N; // Number of matrices.
std::cin >> N;
NM matrices[26]; // 0 for A.
for(int i = 0; i < 26; ++i)
matrices[i].first = matrices[i].second = -1;
for(int i = 0; i < N; ++i) {
String mtx;
std::cin >> mtx;
int mI = mtx[0]-'A';
std::cin >> matrices[mI].first >> matrices[mI].second;
}
String s;
while(std::cin >> s) {
// handle matrix string s:
int idx = 0;
MatrixInfo matrixInfo = parse(s, idx, matrices);
if(matrixInfo.second < 0 )
std::cout << "error" << std::endl;
else
std::cout << matrixInfo.second << std::endl;
}
return 0;
}