package UE07_221024_RegExp3;

import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ChemicalEquations {
    public static void main(String[] args) {
/*
HCl + Na -> NaCl + H2
2 HCl + 2 Na -> 2 NaCl + H2
12 CO2 + 6 H2O -> 2 C6H12O6 + 12 O2
N2 + H2 -> NH3
2 KClO3 -> 2 KCl + 3 O2
CaCO3 + HCl -> CaCl2 + H2O + CO2
C3H8 + 5 O2 -> 3 CO2 + 4 H2O
2 Ag + O2 -> 2 AgO
Fe2O3 + 3 CO -> 2 Fe + 3 CO2
Mg + O2 -> MgO
*/
        Scanner scanner = new Scanner(System.in);
        String input;
        while (!(input = scanner.nextLine()).equals("end"))
            System.out.println((analyze(input) ? "formally correct" : "incorrect") + "\n");
    }

    public static boolean analyze(String formular) {
        String[] s = formular.split("->");
        try {
            Map<String, Integer> first = mapElements(s[0]);
            Map<String, Integer> second = mapElements(s[1]);
            if (first.isEmpty() || second.isEmpty()) return false;
            return first.equals(second);
        } catch (Exception e) {
            return false;
        }
    }

    public static Map<String, Integer> mapElements(String s) {
        Map<String, Integer> elements = new TreeMap<>();
        String[] parts = s.replaceAll(" ", "").split("\\+");
        Pattern pattern = Pattern.compile("\\d*([A-Z][a-z]?|[A-Z])(\\d*)");
        Pattern patternC = Pattern.compile("^(\\d+)[a-zA-Z]+");
        int coefficient;
        int number;
        for (String part : parts) {
            coefficient = 1;
            Matcher matcher = pattern.matcher(part);
            Matcher matcherC = patternC.matcher(part);
            while (matcherC.find()) try {
                coefficient = Integer.parseInt(matcherC.group(1));
            } catch (Exception e) {
                coefficient = 1;
            }
            while (matcher.find()) {
                try {
                    number = Integer.parseInt(matcher.group(2));
                } catch (Exception e) {
                    number = 1;
                }
                elements.put(matcher.group(1), elements.getOrDefault(matcher.group(1), 0) + (number * coefficient));
            }
        }
        return elements;
    }
}
