2020牛客暑期多校第九场 A - Groundhog and 2-Power Representation(栈/pyhton)

传送门


很经典的括号表达式问题,我们可以将 2 ( . . . ) 2(...) 2(...)看做 2 2 2对括号里的数求幂,除去括号的嵌套求幂前一定只有加法,然后最外层一定是加法,这样就能定义运算优先级和最后的求和得出答案,不经常写导致比赛时手生写的慢,特此回顾

对于经典写法,考虑到最后的答案是大数因此写Java

import java.math.BigInteger;
import java.util.*;

public class Main {
    static Stack<Character> st1=new Stack<>();
    static Stack<BigInteger> st2=new Stack<>();

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String s=new String();
        s=scanner.next();
        for(int i=0;i<s.length();i++){
            if(s.charAt(i)>='0' && s.charAt(i)<='9') st2.push(BigInteger.valueOf(s.charAt(i)-'0'));
            else if(s.charAt(i)=='(' || s.charAt(i)=='+') st1.push(s.charAt(i));
            else{
                while(!st1.empty() && st1.peek()!='('){
                    BigInteger a=st2.peek(); st2.pop();
                    BigInteger b=st2.peek(); st2.pop();
                    st2.push(a.add(b));
                    st1.pop();
                }
                st1.pop();
                int n=st2.peek().intValue(); st2.pop();
                BigInteger x=st2.peek(); st2.pop();
                //cout<
                st2.push(x.pow(n));
            }
        }
        while(st2.size()>=2){
            BigInteger a=st2.peek(); st2.pop();
            BigInteger b=st2.peek(); st2.pop();
            st2.push(a.add(b));
        }
        System.out.println(st2.peek());
    }
}

在题解区发现神仙代码,问了朋友发现只需要将前面的左括号替换为求幂的运算,然后执行表达式的值即可,一行解决,orz

print(eval(input().replace('(', '**(')))

你可能感兴趣的:(牛客比赛)