Matrix Chain Multiplication UVA - 442 解题报告

这道题。。。也很水。。。但是没做出来(吐血),简单分析一下原因,这道题跟刚入门stack时的一道题目非常像,然后脑子中就不停的出现,然后就在栈中储存了(,导致整个崩溃,还有就是,忽略了输入符合运算要求,想了很多不该想的,唉,这种题应该是可以拿到的,却总是丢了

题目链接:https://vjudge.net/problem/UVA-442

下面给出AC代码:(最后一些有趣的事情)


#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
const int maxn = 1e6 + 10;

struct node
{
    int rw,cl;
} t[28];


int main()
{
    ios::sync_with_stdio(0);
    int n;  scanf("%d",&n);
    for(int i=1; i<=n; i++)
    {
        char ch;   int a,b;
        scanf(" %c %d %d",&ch,&a,&b);
        t[ch-'A'].rw=a,t[ch-'A'].cl=b;
    }

    string str;
    while(cin>>str)
    {
        int flag=1,len=str.size();
        ll cnt=0;
        stack<node> s;
        for(int i=0; i<len; i++)
        {
            if(str[i]==')')
            {
                node re=s.top();  s.pop();
                node re1=s.top();  s.pop();
                if(re.rw==re1.cl)
                {
                    cnt+=re.cl*re.rw*re1.rw;
                    s.push(node{re1.rw,re.cl});//注意两个矩阵相乘后的到底是什么,不是单独一个数!!!还是一个矩阵
                }
                else
                {
                    flag=0;
                    break;
                }
            }
            else if(str[i]!='(')
                s.push(t[str[i]-'A']);
        }
        if(flag)  printf("%lld\n",cnt);
        else printf("error\n");
    }
    return 0;
}

这道题是AC了没错,但是有一个问题,我使用了cin,会不会效率降低呢?于是我使用了 ios::sync_with_stdio(0);,取消流同步,如果不懂点这里,但是再次提交WA掉了,去网上找了很多资料,最后终于是弄懂了,使用上述的取消流同步后,是不能同时使用scanf与cin的,可能会使读入的东西不符合预期!!!

猜你喜欢

转载自blog.csdn.net/NCC__dapeng/article/details/81951029