upload solutions
This commit is contained in:
72
B/Main.java
Normal file
72
B/Main.java
Normal file
@@ -0,0 +1,72 @@
|
||||
import java.util.*;
|
||||
import java.io.*;
|
||||
|
||||
public class Main {
|
||||
static Map<String, String> parent = new HashMap<>();
|
||||
|
||||
static String find(String i) {
|
||||
if (!parent.containsKey(i)) {
|
||||
parent.put(i, i);
|
||||
return i;
|
||||
}
|
||||
if (parent.get(i).equals(i))
|
||||
return i;
|
||||
String root = find(parent.get(i));
|
||||
parent.put(i, root);
|
||||
return root;
|
||||
}
|
||||
|
||||
static boolean union(String a, String b) {
|
||||
String rootA = find(a);
|
||||
String rootB = find(b);
|
||||
|
||||
if (rootA.equals(rootB))
|
||||
return true;
|
||||
|
||||
boolean isNumA = isNumber(rootA);
|
||||
boolean isNumB = isNumber(rootB);
|
||||
|
||||
if (isNumA && isNumB) {
|
||||
return rootA.equals(rootB);
|
||||
}
|
||||
|
||||
if (isNumA) {
|
||||
parent.put(rootB, rootA);
|
||||
} else {
|
||||
parent.put(rootA, rootB);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws IOException {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
if (!sc.hasNextInt())
|
||||
return;
|
||||
int n = sc.nextInt();
|
||||
|
||||
String[] seq1 = new String[n];
|
||||
String[] seq2 = new String[n];
|
||||
|
||||
for (int i = 0; i < n; i++)
|
||||
seq1[i] = sc.next();
|
||||
for (int i = 0; i < n; i++)
|
||||
seq2[i] = sc.next();
|
||||
|
||||
boolean possible = true;
|
||||
for (int i = 0; i < n; i++) {
|
||||
if (!union(seq1[i], seq2[i])) {
|
||||
possible = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println(possible ? "YES" : "NO");
|
||||
}
|
||||
|
||||
static boolean isNumber(String s) {
|
||||
if (s == null || s.isEmpty())
|
||||
return false;
|
||||
char first = s.charAt(0);
|
||||
return (first >= '0' && first <= '9') || (first == '-' && s.length() > 1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user