|
| 1 | +```java |
| 2 | + |
| 3 | +import java.io.BufferedReader; |
| 4 | +import java.io.IOException; |
| 5 | +import java.io.InputStreamReader; |
| 6 | +import java.util.StringTokenizer; |
| 7 | + |
| 8 | + |
| 9 | +public class Main { |
| 10 | + |
| 11 | + |
| 12 | + static StringBuilder sb = new StringBuilder(); |
| 13 | + static int cityCnt,planCityCnt; |
| 14 | + static int[][] arr; |
| 15 | + static int[] plan,parent; |
| 16 | + |
| 17 | + |
| 18 | + public static void main(String[] args) throws IOException { |
| 19 | + init(); |
| 20 | + process(); |
| 21 | + print(); |
| 22 | + } |
| 23 | + |
| 24 | + private static void init() throws IOException { |
| 25 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 26 | + cityCnt = Integer.parseInt(br.readLine()); |
| 27 | + planCityCnt = Integer.parseInt(br.readLine()); |
| 28 | + arr = new int[cityCnt][cityCnt]; |
| 29 | + parent = new int[cityCnt]; |
| 30 | + for (int i = 0; i < cityCnt; i++) { |
| 31 | + parent[i] = i; |
| 32 | + } |
| 33 | + plan = new int[planCityCnt]; |
| 34 | + |
| 35 | + for (int i = 0; i < cityCnt; i++) { |
| 36 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 37 | + for (int j = 0; j < cityCnt; j++) { |
| 38 | + arr[i][j] = Integer.parseInt(st.nextToken()); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 43 | + for (int i = 0; i < planCityCnt; i++) { |
| 44 | + plan[i] = Integer.parseInt(st.nextToken())-1; |
| 45 | + } |
| 46 | + |
| 47 | + } |
| 48 | + |
| 49 | + private static void process() throws IOException { |
| 50 | + for (int i = 0; i < cityCnt; i++) { |
| 51 | + for (int j = 0; j < cityCnt; j++) { |
| 52 | + if (arr[i][j] == 1) union(i,j); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + for (int i = 1; i < planCityCnt; i++) { |
| 57 | + int preRoot = find(plan[i-1]); |
| 58 | + int curRoot = find(plan[i]); |
| 59 | + if (preRoot != curRoot) { |
| 60 | + System.out.println("NO"); |
| 61 | + return; |
| 62 | + } |
| 63 | + } |
| 64 | + |
| 65 | + System.out.println("YES"); |
| 66 | + |
| 67 | + } |
| 68 | + |
| 69 | + private static void union(int a, int b) { |
| 70 | + int aRoot = find(a); |
| 71 | + int bRoot = find(b); |
| 72 | + |
| 73 | + if (aRoot == bRoot) return; |
| 74 | + |
| 75 | + if (aRoot > bRoot) { |
| 76 | + parent[bRoot] = aRoot; |
| 77 | + } else { |
| 78 | + parent[aRoot] = bRoot; |
| 79 | + } |
| 80 | + |
| 81 | + } |
| 82 | + |
| 83 | + private static int find(int x) { |
| 84 | + if (x == parent[x]) return x; |
| 85 | + |
| 86 | + return parent[x] = find(parent[x]); |
| 87 | + } |
| 88 | + |
| 89 | + |
| 90 | + |
| 91 | + private static void print() { |
| 92 | + System.out.print(sb.toString()); |
| 93 | + } |
| 94 | +} |
| 95 | +``` |
0 commit comments