Problem 428
Satisfiability of Equality Equations
Medium · 20 pts · Graph, Union Find, String
Problem
You are given equations between single-letter variables, each written as 'a==b' or 'a!=b'. Decide whether there is a way to assign an integer to every variable so that all the equations are true at the same time. Process all the '==' equations first, merging equal variables into groups with union-find; then the answer is NO exactly when some '!=' equation compares two variables in the same group (including a variable compared with itself).
Input
First line: N. Second line: the N equations separated by spaces.
Output
Print YES if all equations can be satisfied, otherwise NO.
Constraints
1 <= N <= 500; variables are lowercase letters
Example input
2 a==b b!=a
Example output
NO
Explanation
'a==b' and 'b!=a' contradict each other: the first forces a and b to be equal, and the second says they are not. So the answer is NO.