/* ACM North Central Region, 1993-94 Problem D, Evaluating Simple C Expressions Ed Karrels, April 1998 */ import ContestSolution; import java.io.*; class Tokenizer { public void init(String str0) { str = str0; pos = 0; } public char next() { while (pos < str.length() && (str.charAt(pos) == ' ' || str.charAt(pos) == '\t')) pos++; if (pos == str.length()) return 0; if (str.charAt(pos) == '+') { if (str.charAt(pos+1) == '+') { pos += 2; return '*'; } else { pos++; return '+'; } } if (str.charAt(pos) == '-') { if (str.charAt(pos+1) == '-') { pos += 2; return '/'; } else { pos++; return '-'; } } return str.charAt(pos++); } private String str; private int pos; }; public class acmreg93d implements ContestSolution { public static void main(String[] args) { acmreg93d soln = new acmreg93d(); soln.do_it(System.in, System.out); } public void do_it(InputStream input, PrintStream output) { DataInputStream line_input = new DataInputStream(input); String line; char token; int i, p, pre, sign, sum, varno; Tokenizer tokens = new Tokenizer(); // the value of each variable int[] values = new int[26]; // the offset to be added to the variable after evaluation int[] postfix_offset = new int[26]; // whether each variable was used boolean[] var_used = new boolean[26]; while (true) { // read a line of input try { line = line_input.readLine(); } catch (IOException e) { output.println("Input read error"); return; } // terminate on a blank line or EOF if (line == null || line.equals("")) return; output.println("Expression: " + line); // initialize variables for (i=0; i<26; i++) { values[i] = i+1; var_used[i] = false; postfix_offset[i] = 0; } sign = 1; sum = 0; tokens.init(line); // get the first token token = tokens.next(); while (true) { pre = 0; // pre-increment if (token == '*') {pre++; token = tokens.next();} // pre-decrement if (token == '/') {pre--; token = tokens.next();} // must be a variable name here if (!Character.isLetter(token)) { output.println("no var name"); return; } varno = token - 'a'; // adjust the variable if it was preceded by ++ or -- values[varno] += pre; // mark this variable as having been used var_used[varno] = true; // add this term of the expression sum += sign * values[varno]; // check for a postfix operator or then next + or - token = tokens.next(); // post-increment if (token == '*') { postfix_offset[varno]++; token = tokens.next(); } // post-decrement if (token == '/') { postfix_offset[varno]--; token = tokens.next(); } // end of line if (token == 0) break; // if there's a plus here, add the next term, otherwise // subtract it sign = (token == '+') ? 1 : -1; // get the next token token = tokens.next(); } // print the value of the expression and the values // of all the variable used output.println(" value = " + sum); for (i=0; i<26; i++) { if (var_used[i]) { output.println(" " + (char)('a' + i) + " = " + (postfix_offset[i] + values[i])); } } } } }