Topic Link: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=103&page=show_ problem&problem=383
Type of topic: data structure, linked list
Sample input:
9 (
A)
5
D/
F 5
G/5
H I (a)
b
c
(AA)
(AB)
(AC)
(A (BC))
((AB) C) ((
(((()) ((((
D)) ((((DE) f) (((()) (((()) ((()) ((()) ((( (
(D (EF)) ((GH) I)
Sample output:
0
0
0
error
10000
error
3500
15000
40500
47500
15125
The main effect of the topic:
Given a series of matrices, give them a name of a, B ... And their number of rows and columns. When you're done, you give a series of expressions, and then you ask how many multiplication steps you can take to calculate by these expressions.
This article URL address: http://www.bianceng.cn/Programming/sjjg/201410/45537.htm
The idea of disintegration:
The question is similar to that of the bracket. The key step is to compute this process of matrix multiplication times.
#include <cstdio> #include <cctype> #include <cstring> #include <cstdlib> #include <STACK&G
T
using namespace Std;
int sum,n;
int mat[30][2];
int arr[30],prev[30], next[30];
Char str[1000];
void Solve () {//If there is only one matrix, then direct output 0 if (strlen (str) ==1 && isupper (str[0)) {printf ("0\n");
} else{Char copymat[30][2];
int i,j; Copy an array to operate.
Because the following operations need to modify these matrices for (i=0 i<n; ++i) {copymat[i][0] = mat[i][0];
COPYMAT[I][1] = mat[i][1];
} sum=0;
stack<char>st;
For (i=0 I<strlen (str); ++i) {if (str[i]== ' (' | | isupper (str[i)) St.push (str[i));
else if (str[i]== ') ') {stack<char>temp; When encountering ') ', take out all the matrices in the stack to compute while (Isupper (St.top ())) {Temp.push (St.top ()));
St.pop ();
}//Put ' (' also pop-up st.pop ();
Char ex;
Remove the first matrix (the leftmost one in the original expression) if (!temp.empty ()) {ex=temp.top ();
Temp.pop ();
while (!temp.empty ()) {Char multi = temp.top ();
Temp.pop ();
If the number of columns on the left matrix differs from the function of the right matrix, the direct output error if (copymat[ex-' a '][1]!= copymat[multi-' a '][0]) {
printf ("error\n");
return; //Count multiplication, plus sum + = copymat[ex-' A '][0]*copymat[multi-' a '][0]*copymat[multi-'
A '][1];
Multiply to get a new matrix, update the size copymat[ex-' a '][1] = copymat[multi-' a '][1];
} St.push (ex);
}
} printf ("%d\n", sum);
int main () {freopen ("Input.txt", "R", stdin);
Char ch;
int I, J;
scanf ("%d%*c", &n);
For (i=0 i<n; ++i) {scanf ("%c%d%d%*c", &ch,&mat[i][0],&mat[i][1]);
while (gets (str)) {solve ();
return 0; }