Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- int n;
- String[] dict;
- boolean[][] isChecked;
- private int getPrefixLength(String a, int posA, String b, int posB) {
- int result = 0;
- while (result + posA < a.length() && result + posB < b.length()
- && a.charAt(result + posA) == b.charAt(result + posB)) {
- result++;
- }
- return result;
- }
- private boolean slv(String str, int pos, int ind) {
- boolean result = false;
- if (isChecked[ind][pos]) {
- return false;
- }
- isChecked[ind][pos] = true;
- int commonPrefix;
- for (int i = 0; i < dict.length && !result; i++) {
- commonPrefix = getPrefixLength(str, pos, dict[i], 0);
- if (commonPrefix != Math.min(str.length() - pos, dict[i].length())) {
- continue;
- }
- if (pos + commonPrefix == str.length() && commonPrefix == dict[i].length()) {
- return true;
- }
- if (pos + commonPrefix == str.length()) {
- if (!isChecked[i][commonPrefix]) {
- result |= slv(dict[i], commonPrefix, i);
- }
- } else {
- if (!isChecked[ind][pos + commonPrefix]) {
- result |= slv(str, pos + commonPrefix, ind);
- }
- }
- }
- return result;
- }
- public void solve() throws NumberFormatException, IOException {
- n = nextInt();
- dict = new String[n];
- isChecked = new boolean[n][];
- for (int i = 0; i < dict.length; i++) {
- dict[i] = in.readLine();
- isChecked[i] = new boolean[dict[i].length()];
- for (int j = 0; j < dict[i].length(); j++) {
- isChecked[i][j] = false;
- }
- }
- for (int i = 0; i < n - 1; i++) {
- for (int j = i + 1; j < n; j++) {
- int ind = i;
- String a = dict[i];
- String b = dict[j];
- int com = getPrefixLength(a, 0, b, 0);
- if (com != Math.min(a.length(), b.length())) {
- continue;
- }
- if (b.length() > a.length()) {
- a = b;
- ind = j;
- }
- if (isChecked[ind][com]) {
- continue;
- }
- if (slv(a, com, ind)) {
- out.println("YES");
- return;
- }
- }
- }
- out.println("NO");
- }
Advertisement
Add Comment
Please, Sign In to add comment