UVA 442 Matrix Chain Multiplication ( stack 应用)

来源:互联网 发布:甄子丹功夫怎么样知乎 编辑:程序博客网 时间:2024/06/05 04:23



【思路】

因为只需要考虑字母,不需要考虑(),  所以  遇到(跳过 遇到 )  出栈 进行计算,   存完后把结果记录, 并将组合后的矩阵进栈

我直接存的 数值, 因此需要出栈4次 分别为 y2,x2,y1,x1 


【代码】

//#include <bits/stdc++.h>#include <iostream>#include <stdio.h>#include <algorithm>#include <cmath>#include <math.h>#include <cstring>#include <string>#include <queue>#include <stack>#include <stdlib.h>#include <list>#include <map>#include <set>#include <bitset>#include <vector>#define mem(a,b) memset(a,b,sizeof(a))#define findx(x) lower_bound(b+1,b+1+bn,x)-b#define FIN      freopen("input.txt","r",stdin)#define FOUT     freopen("output.txt","w",stdout)#define S1(n)    scanf("%d",&n)#define SL1(n)   scanf("%I64d",&n)#define S2(n,m)  scanf("%d%d",&n,&m)#define SL2(n,m)  scanf("%I64d%I64d",&n,&m)#define Pr(n)     printf("%d\n",n)#define lson rt << 1, l, mid#define rson rt << 1|1, mid + 1, r#define mem(a,b) memset(a,b,sizeof(a))typedef long long ll;const int INF=0x3f3f3f3f;const ll MOD=1e8;const int MAXN=1e5+5;const int N=105;ll qpow(ll x,ll n){ll res=1;for(;n;n>>=1){if(n&1)res=(res*x);x=(x*x);}return res;}using namespace std;struct node{    char s;    int x,y;}a[MAXN];int main(){    int n;    cin>>n;    int flag;    map<char,int> mp;    string str;    stack<int> S,ANS;    for(int i=1;i<=n;i++)    {        getchar();        scanf("%c %d %d",&a[i].s,&a[i].x,&a[i].y);        if(!mp[a[i].s])            mp[a[i].s]=i;    }    while(cin>>str)    {        int len=str.length();        flag=0;        int ans=0;        for(int i=0;i<len&&!flag;i++)        {            if(str[i]=='(')                continue;            else if(str[i]<='Z'&&str[i]>='A')                S.push(a[mp[str[i]]].x),S.push(a[mp[str[i]]].y);            else if(str[i]==')')            {                int y2=S.top();                S.pop();                int x2=S.top();                S.pop();                int y1=S.top();                S.pop();                int x1=S.top();                S.pop();                //printf("(%d,%d) ||(%d,%d) \n",x1,y1,x2,y2);                if(x2!=y1)                {                    flag=1;                    break;                }                else                {                    ans+= (x1*y1)*y2;                    S.push(x1);                    S.push(y2);                }            }        }        if(flag)        {            printf("error\n");            continue;        }        printf("%d\n",ans);    }    return 0;}


123

原创粉丝点击