FZU 1061 矩阵连乘
生活随笔
收集整理的這篇文章主要介紹了
FZU 1061 矩阵连乘
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
用棧來算一算就可以了。
#include<iostream> #include<algorithm> #include<cstdio> #include<cstring> #include<map> using namespace std;struct Mar {int r,c; } mar[300]; int n; char s[3000]; int r,c,top,flag; Mar Stack[300];int main() {while(~scanf("%d",&n)){for(int i=0; i<n; i++){scanf("%s%d%d",s,&r,&c);mar[s[0]-'A'].r=r;mar[s[0]-'A'].c=c;}scanf("%s",s);int len=strlen(s);flag=0;top=-1;for(int i=0; i<len; i++){if(top==-1){top++;if(s[i]>='A'&&s[i]<='Z')Stack[top]=mar[s[i]-'A'];else{Mar node;node.c=-1;node.r=-1;Stack[top]=node;}continue;}if(s[i]=='('){Mar node;node.c=-1;node.r=-1;top++;Stack[top]=node;}else if(s[i]==')'){top--;Stack[top]=Stack[top+1];if(top-1!=-1&&Stack[top-1].c!=-1&&Stack[top-1].r!=-1){if(Stack[top-1].c!=Stack[top].r){flag=-1;break;}else{flag=flag+Stack[top-1].c*Stack[top-1].r*Stack[top].c;Stack[top-1].c=Stack[top].c;top--;}}}else{Mar node;node.c=mar[s[i]-'A'].c;node.r=mar[s[i]-'A'].r;top++;Stack[top]=node;if(Stack[top-1].r!=-1&&Stack[top-1].c!=-1){if(Stack[top-1].c!=Stack[top].r){flag=-1;break;}else{flag=flag+Stack[top-1].c*Stack[top-1].r*Stack[top].c;Stack[top-1].c=Stack[top].c;top--;}}}}if(flag==-1) printf("error\n");else printf("%d\n",flag);}return 0; }?
轉載于:https://www.cnblogs.com/zufezzt/p/5289488.html
總結
以上是生活随笔為你收集整理的FZU 1061 矩阵连乘的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VC++ 监控指定目录改变
- 下一篇: STL算法algorithm,