codeforces-gym-100187-J【dfs】

题目链接:点击打开链接

J. Deck Shuffling
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

The world famous scientist Innokentiy continues his innovative experiments with decks of cards. Now he has a deck of n cards and kshuffle machines to shuffle this deck. As we know, i-th shuffle machine is characterized by its own numbers pi, 1pi, 2, ..., pi, n such that if one puts n cards numbered in the order 12...n into the machine and presses the button on it, cards will be shuffled forming the deckpi, 1pi, 2, ..., pi, n where numbers pi, 1pi, 2, ..., pi, n are the same numbers of cards but rearranged in some order.

At the beginning of the experiment the cards in the deck are ordered as a1a2, ..., an, i.e. the first position is occupied by the card with number a1, the second position — by the card with number a2, and so on. The scientist wants to transfer the card with number x to the first position. He can use all his shuffle machines as many times as he wants. You should determine if he can reach it.

Input

In the first line the only positive integer n is written — the number of cards in the Innokentiy's deck.

The second line contains n distinct integers a1a2, ..., an (1 ≤ ai ≤ n) — the initial order of cards in the deck.

The third line contains the only positive integer k — the number of shuffle machines Innokentiy has.

Each of the next k lines contains n distinct integers pi, 1pi, 2, ..., pi, n (1 ≤ pi, j ≤ n) characterizing the corresponding shuffle machine.

The last line contains the only integer x (1 ≤ x ≤ n) — the number of card Innokentiy wants to transfer to the first position in the deck.

Numbers n and k satisfy the condition 1 ≤ n·k ≤ 200000.

Output

Output «YES» if the scientist can transfer the card with number x to the first position in the deck, and «NO» otherwise.

Examples
input
4
4 3 2 1
2
1 2 4 3
2 3 1 4
1
output
YES
input
4
4 3 2 1
2
1 2 4 3
2 1 3 4
1
output
NO

大意:给你一堆牌,给你 k 个洗牌机,给你洗牌机洗完之后的顺序,然后问你是否洗完牌之后,第一张牌为 x

思路:建边,跑一发 dfs 就好了,其实就问你第一个位置和 x 所在的位置是否联通

#include
#include
#include
#include
#include
using namespace std;
typedef pair pii;
int n,k;
int a[200010];
bool vis[200010];
vector v[200010];
map mp;
bool flag;
void dfs(int x)
{
	if(x==1)
	{
		flag=1;
		return ;	
	}
	if(vis[x])
		return ;
	vis[x]=1;
	for(int i=0;i



你可能感兴趣的:(DFS,Codeforces)