๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/๋ฌธ์ œ

[์ž๋ฐ”] ๋ฐฑ์ค€ 1976 - ์—ฌํ–‰ ๊ฐ€์ž

by applemango2021 2021. 1. 2.

์ตœ๋‹จ ๊ฒฝ๋กœ๋ฅผ ์ฐพ๋Š” ๊ฒƒ๋„ ์•„๋‹ˆ๊ณ , ๋‹ค๋ฅธ ๋„์‹œ๋ฅผ ๊ฑฐ์ณ์„œ๋ผ๋„ ๋“ค๋ฅผ ์ˆ˜๋งŒ ์žˆ์œผ๋ฉด ๋œ๋‹ค. 

์œ ๋‹ˆ์˜จ ํŒŒ์ธ๋“œ๋กœ ๊ฐ ๋„์‹œ๋“ค์˜ ์ตœ์ƒ์œ„ parent๋ฅผ ์ฐพ๊ณ , ๊ฒฝ๋กœ์ƒ์˜ ๋„์‹œ๋“ค์ด ๊ฐ™์€ parent์ธ์ง€๋งŒ ์ฒดํฌํ•˜๋ฉด ๋œ๋‹ค. 

/* 2021.01.02(ํ† ) */
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Main{
	
	static int[] parent;
	public static void main(String[] args) throws Exception{
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		int N = Integer.parseInt(br.readLine().trim());
		int M = Integer.parseInt(br.readLine().trim());
		
		parent = new int[N+1];
		for(int i=1;i<=N;i++) parent[i] = i;

		//์œ ๋‹ˆ์˜จ ๊ณผ์ • 
		String[] str;
		int start,end, value;
		for(int a=1;a<=N;a++) {
			str = br.readLine().trim().split(" ");
			start = a;
			for(int b=1;b<=N;b++) {
				value = Integer.parseInt(str[b-1]);
				
				if(value==0) continue;
				end = b;
				union(start,end);
			}
		}
		
		//๊ฒฝ๋กœ ์ฒดํฌ
		str = br.readLine().trim().split(" ");
		int prevParent = -1;
		int city;
		String result = "YES";
		for(int i=0;i<M;i++) {
			city = Integer.parseInt(str[i]);
			if(i==0) prevParent = parent[city];
			
			if(prevParent!=find(city)) {
				result = "NO";
				break;
			}
		}
		System.out.println(result);
	}

	private static void union(int start, int end) {
		start = find(start);
		end = find(end);
		
		if(start==end) return;
		if(start<end) {
			parent[end] = start;
		}else if(start>end){
			parent[start] = end;
		}
	}

	private static int find(int n) {
		if(parent[n]==n) return n;
		return parent[n] = find(parent[n]);
	}
}