http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=383
//type:stack import java.util.*; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); Matrix[] matrix = new Matrix[26]; int num = scan.nextInt(); int index=0; while(num--!=0){ //The first part char name = (scan.next()).toCharArray()[0]; int row = scan.nextInt(); int column = scan.nextInt(); scan.nextLine(); matrix[(int)(name)-65]=new Matrix(name,row,column);/*-65的用意;把字母從0開始排列, 大A的Ascii碼從65開始,配合26字母Matrix擺放*/ } A: while(scan.hasNext()){//The second part int total=0; Stack<Matrix> m = new Stack<Matrix>(); String exp = scan.nextLine(); for(int i=0 ; i<exp.length() ; i++){ if(exp.charAt(i)=='('){ } else if(exp.charAt(i)==')'){ Matrix rightM = m.pop(); //先進後出,stack的特性 Matrix leftM = m.pop(); if(leftM.column!=rightM.row){ System.out.println("error"); continue A; } else{ total+=leftM.row*leftM.column*rightM.column; m.push(new Matrix('t',leftM.row,rightM.column)); } } else//沒有以上狀況就是matrix,放入stack裡 m.push(matrix[(int)exp.charAt(i)-65]); } //到了最右邊的)跳出後,會有三種情況,一個是stack裡面剩一個matrix;剩兩個;剩三個以上 if(m.size()>2){ System.out.println("error"); continue A; } else if(m.size()==2){ Matrix rightM = m.pop(); Matrix leftM = m.pop(); if(leftM.column!=rightM.row){ System.out.println("error"); continue A; } else total+=leftM.row*leftM.column*rightM.column; } System.out.println(total); } } } class Matrix{ public char matrix; public int row,column; public Matrix(char matrix,int row,int column){ this.matrix=matrix; this.row=row; this.column=column; } }
沒有留言:
張貼留言