zoukankan      html  css  js  c++  java
  • 【Miscalculation UVALive

    题目分析

    题目讲的是给你一个串,里面是加法、乘法混合运算(个人赛中误看成是加减乘除混合运算),有两种算法,一种是乘法优先运算,另一种是依次从左向右运算(不管它是否乘在前还是加在前)。
    个人赛中试着模拟了一下,TLE了,又尝试优化,还是TLE,T了四发,最终以崩溃结束。回去看了看别人代码,发现此题直接模拟即可(至于当时为啥TLE可能与我两个两个的读入有关,其实直接读入字符串即可,具体操作后面进行)。
    分析:从左向右运算的这里就不再赘述,主要讲一下乘法优先运算如何去写。可以将数字都存入到一个数组中,然后遍历字符串(主要找中间的符号位),找到加号先不用管,找到乘号时就用它的后一位乘以它的前一位(这里的它就是那个乘号,也就是第二个数字乘以第一个数字,赋值给第二个数字),然后将它的前一位赋值为0。最后遍历这个int数组,直接都加起来即可。

    AC代码

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    using namespace std;
    typedef long long LL;
    const int maxn = 1000000;
    char s[maxn];
    int digit[maxn], sum;
    int main()
    {
        // freopen("input.txt", "r", stdin);
        // freopen("output.txt", "w", stdout);
        while(scanf("%s", s) != EOF)
        {
            scanf("%d", &sum);
            int len = strlen(s);
            memset(digit, 0, sizeof(digit));
            int s1 = 0, s2 = 0;
            s1 = int(s[0]-'0');
            for(int i = 1; i < len; )
            {
                if(s[i] == '+')
                    s1 += int(s[i+1]-'0');
                else if(s[i] == '*')
                    s1 *= int(s[i+1]-'0');
                i += 2;
            }
            
            for(int i = 0; i < len; i = i + 2)
                digit[i] = int(s[i] - '0');     //将数字存储在一个int数组中
            for(int i = 0; i < len; i++)
            {
                if(s[i] == '*')
                {
                    digit[i+1] *= digit[i-1];       //后一位乘以前一位,然后赋值给后一位
                    digit[i-1] = 0;         //将前一位整成0
                }
                else
                    continue;
            }
            for(int i = 0; i < len; i++)
                s2 += digit[i];             //都加起来就可以了
            if(s1 == sum && s2 == sum)
                printf("U");
            else if(s1 == sum)
                printf("L");
            else if(s2 == sum)
                printf("M");
            else 
                printf("I");
            printf("
    ");
        }
        
    }
    
  • 相关阅读:
    链接
    列表
    Android Studio AVD 虚拟机 联网 失败
    docker error during connect: Get http://%2F%2F.%2Fpipe%2Fdocker_engine/v1.29/containers/json: open //./pipe/docker_engine: The system cannot find the file specified. In the default daemon configuratio
    JSP Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING
    js jsp form
    intellij jsp 中文乱码
    [转载]在Intellij Idea中使用JSTL标签库
    windows pybloomfilter
    docker mysql
  • 原文地址:https://www.cnblogs.com/KeepZ/p/11502634.html
Copyright © 2011-2022 走看看