CSP201912-3化学方程式 Java

试题编号: 201912-3
试题名称: 化学方程式
时间限制: 1.0s
内存限制: 512.0MB

代码:

import java.util.Map;
import java.util.HashMap;
import java.util.Scanner;
public class Main{
	static Map<String, Integer> left = new HashMap<>();
	static Map<String, Integer> right = new HashMap<>();
	
	public static void addput(Map<String, Integer> m, String s, int num){
		if(m.containsKey(s)) {
			int newnum = num+m.get(s);
			m.put(s, newnum);
		}
		else
			m.put(s, num);
	}
	
	public static void formula(String str, int l, int r, int coef) {
		int digits = 1;
		int i = l, j = 0;
		while(str.charAt(i)>='0'&&str.charAt(i)<='9') {
			j = j*10+(int)(str.charAt(i)-'0');
			i++;
		}
		coef = Math.max(coef, coef*j);
		while(i<=r) {
			j = 0;
			digits=1;
			if(str.charAt(i)=='(') {
				int hel = 1;
				int rr = i;
				while(rr<=r&&hel!=0) {
					rr++;
					if(str.charAt(rr)=='(') hel++;
					else if(str.charAt(rr)==')') hel--;
				}
				int k = rr+1;
				while(k<=r&&str.charAt(k)<='9'&&str.charAt(k)>='0') {
					j= j*10+(int)(str.charAt(k)-'0');
					k++;
				}
				digits = Math.max(digits, digits*j);
				formula(str, i+1, rr-1, coef*digits);
				i = k;
				continue;
			}
			if(str.charAt(i)==')') {
				i++;
				continue;
			}
			String s = str.charAt(i)+"";
			i++;
			if(i<=r&&str.charAt(i)>='a'&&str.charAt(i)<='z') {
				s+=str.charAt(i)+"";
				i++;
			}
			while(i<=r&&str.charAt(i)>='0'&&str.charAt(i)<='9') {
				j= j*10+(int)(str.charAt(i)-'0');
				i++;
			}
			digits = Math.max(digits, digits*j);
			if(r<str.indexOf("=")) 
				addput(left, s, coef*digits);
			else
				addput(right, s, coef*digits);
			
		}
		
	}
	
	public static void expr(String str, int l, int r) {
		int ap = str.indexOf('+',l);
		if(ap<0||ap>r) {
			formula(str, l, r, 1);
			return ;
		}
		formula(str, l, ap-1, 1);
		if(str.indexOf('+',ap+1)>ap+1&&str.indexOf('+',ap+1)<r)
			expr(str, ap+1, r);
		else
			formula(str, ap+1,r, 1);
	}
	
	public static boolean isEquation(String str) {
		int l = 0, r = str.length()-1;
		int ep = str.indexOf('=');
		expr(str,l,ep-1);
		expr(str,ep+1,r);
		if(left.equals(right)) return true;
		else return false;
	}
	
	public static String YorN(String str) {
		if(isEquation(str)) return "Y";
		else return "N";
	}
	
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		String res = "";
		for(int i=0;i<n;i++) {
			left.clear();
			right.clear();
			String str = in.next();
			res+=YorN(str);
			/*
			System.out.print("left:");
			for(String key:left.keySet()) System.out.print(key+":"+left.get(key)+" ");
			System.out.println();
			System.out.print("right:");
			for(String key:right.keySet()) System.out.print(key+":"+right.get(key)+" ");
			*/
		}
		for(int i=0;i<n;i++) 
			System.out.println(res.charAt(i)+"");
		in.close();
	}
}

猜你喜欢

转载自blog.csdn.net/qq_18287147/article/details/106981698