#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
typedef long long int64;
const int inf=0x7FFFFFFF;
#define show(x) cout << x << endl
#define rep(i,n) for(int i=0;i<n;i++)
#define mset(a,i) memset(a,i,sizeof(a))
#define PB(i) push_back(i)

using namespace std;
#define MAX_N 201
int c[MAX_N], g[MAX_N][MAX_N], deg[MAX_N];
int in[MAX_N];
int N;

int topsort(int cur) {
	rep(i, N)
		in[i] = deg[i];
	int ret = 0, cnt = 0, u;
	while(cnt < N) {
		u = -1;
		rep(i, N)if(in[i] == 0 && c[i] == cur) {
			u = i;
			break;
		}
		if(u == -1) {
			cur ++;
			ret ++;
			if(cur == 4)
				cur = 1;
		}
		ret ++;
		cnt ++;
		in[u] = -1;
		rep(v, N)
			if(g[u][v]) {
				in[v] --;
			}
	}
	return ret;
}

int main() {
	cin >> N;
	rep(i, N)
		cin >> c[i];
	for(int i = 0, v, tot; i < N; i ++) {
		scanf("%d", &tot);
		while(tot --) {
			scanf("%d", &v);
			v --;
			deg[i] ++;
			g[v][i] = true;
		}
	}
	int ans = inf;
	for(int i = 1; i <= 3; i ++)
		ans = min(ans, topsort(i));
	cout << ans << endl;
	return 0;
}


#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <string>
#include <cstring>
#include <algorithm>
typedef long long int64;
const int inf=0x7FFFFFFF;
#define show(x) cout << x << endl
#define rep(i,n) for(int i=0;i<n;i++)
#define mset(a,i) memset(a,i,sizeof(a))
#define PB(i) push_back(i)

using namespace std;
#define MAX_N 201
int c[MAX_N], g[MAX_N][MAX_N], deg[MAX_N];
int in[MAX_N];
int N;

int topsort(int cur) {
	rep(i, N)
		in[i] = deg[i];
	int ret = 0, cnt = 0, u;
	while(cnt < N) {
		u = -1;
		rep(i, N)if(in[i] == 0 && c[i] == cur) {
			u = i;
			break;
		}
		if(u == -1) {
			cur ++;
			ret ++;
			if(cur == 4)
				cur = 1;
			continue;
		}
		ret ++;
		cnt ++;
		in[u] = -1;
		rep(v, N)
			if(g[u][v]) {
				in[v] --;
			}
	}
	return ret;
}

int main() {
	cin >> N;
	rep(i, N)
		cin >> c[i];
	for(int i = 0, v, tot; i < N; i ++) {
		scanf("%d", &tot);
		while(tot --) {
			scanf("%d", &v);
			v --;
			deg[i] ++;
			g[v][i] = true;
		}
	}
	int ans = inf;
	for(int i = 1; i <= 3; i ++)
		ans = min(ans, topsort(i));
	cout << ans << endl;
	return 0;
}


#include<bits/stdc++.h>

using namespace std;

#define MAXN 205
#define MAXM (MAXN*MAXN)
#define endline "\n"

int head[MAXN],to[MAXM],nxt[MAXM],id=1;
int indeg[MAXN],ori_indeg[MAXN];
int comp[MAXN];
int stk[3][MAXN],stkID[3];
int n;

void addedge(int f,int t)
{
    nxt[id]=head[f];
    head[f]=id;
    to[id++]=t;
}

void visit(int cur)
{
    for(int i=head[cur];i;i=nxt[i])
        if(--indeg[to[i]]==0)
            stk[comp[to[i]]][stkID[comp[to[i]]]++]=to[i];
}

int solve(int beg)
{
    for(int i=0;i<n;i++)
        if(indeg[i]==0)
            stk[comp[i]][stkID[comp[i]]++]=i;
    int cur=beg;
    int ret=0;
    while(stkID[0] || stkID[1] || stkID[2])
    {
        while(stkID[cur])
            visit(stk[cur][--stkID[cur]]),ret++;
        cur=(cur+1)%3;
        if(stkID[0] || stkID[1] || stkID[2])
            ret++;
    }
    return ret;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>comp[i],comp[i]--;
    for(int i=0;i<n;i++)
    {
        int num;
        cin>>num;
        while(num--)
        {
            int t;
            cin>>t;
            t--;
            addedge(i,t);
            ori_indeg[t]++;
        }
    }
    int mn=1e9;
    for(int i=0;i<3;i++)
    {
        memcpy(indeg,ori_indeg,sizeof indeg);
        mn=min(mn,solve(i));
    }
    cout<<mn<<endline;
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

#define MAXN 205
#define MAXM (MAXN*MAXN)
#define endline "\n"

int head[MAXN],to[MAXM],nxt[MAXM],id=1;
int indeg[MAXN],ori_indeg[MAXN];
int comp[MAXN];
int stk[3][MAXN],stkID[3];
int n;

void addedge(int f,int t)
{
    nxt[id]=head[f];
    head[f]=id;
    to[id++]=t;
}

void visit(int cur)
{
    for(int i=head[cur];i;i=nxt[i])
        if(--indeg[to[i]]==0)
            stk[comp[to[i]]][stkID[comp[to[i]]]++]=to[i];
}

int solve(int beg)
{
    for(int i=0;i<n;i++)
        if(indeg[i]==0)
            stk[comp[i]][stkID[comp[i]]++]=i;
    int cur=beg;
    int ret=0;
    while(stkID[0] || stkID[1] || stkID[2])
    {
        while(stkID[cur])
            visit(stk[cur][--stkID[cur]]),ret++;
        cur=(cur+1)%3;
        if(stkID[0] || stkID[1] || stkID[2])
            ret++;
    }
    return ret;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    cin>>n;
    for(int i=0;i<n;i++)
        cin>>comp[i],comp[i]--;
    for(int i=0;i<n;i++)
    {
        int num;
        cin>>num;
        while(num--)
        {
            int f;
            cin>>f;
            f--;
            addedge(f,i);
            ori_indeg[i]++;
        }
    }
    int mn=1e9;
    for(int i=0;i<3;i++)
    {
        memcpy(indeg,ori_indeg,sizeof indeg);
        mn=min(mn,solve(i));
    }
    cout<<mn<<endline;
    return 0;
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <numeric>
#include <functional>
#include <algorithm>

using namespace std;

const int N = 255;
const int INF = 0x3f3f3f3f;

bool mat[N][N];
int val[N];
int ind[N], mem_ind[N];
int topo[N];
int n;

void toposort()
{
    int front = 0, rear = 0;
    for (int i = 1; i <= n; i++)
        if (ind[i] == 0)
            topo[rear++] = i;
    while (front < rear)
    {
        int u = topo[front++];
        for (int i = 1; i <= n; i++)
        {
            if (mat[u][i])
            {
                ind[i]--;
                if (ind[i] == 0)
                    topo[rear++] = i;
            }
        }
    }
}

int calc(int pos)
{
    memcpy(ind, mem_ind, sizeof (int) * (n + 1));
    bool vis[N] = {};
    int rem = n, cost = 0;
    for (; rem; pos = (pos + 1) % 3, cost++)
    {
        for (int i = 0; i < n; i++)
        {
            int u = topo[i];
            if (!vis[u] && ind[u] == 0 && val[u] == pos)
            {
                cost++;
                rem--;
                for (int v = 1; v <= n; v++)
                    if (mat[u][v])
                        ind[v]--;
                vis[u] = true;
            }
        }
    }
    return cost - 1;
}

int main()
{
    while (scanf("%d", &n) == 1)
    {
        memset(mat, 0, sizeof (mat));
        memset(ind, 0, sizeof (ind));
        for (int i = 1; i <= n; i++)
            scanf("%d", val + i), val[i]--;
        for (int i = 1; i <= n; i++)
        {
            int k, v;
            scanf("%d", &k);
            while (k--)
            {
                scanf("%d", &v);
                mat[v][i] = true;
                ind[i]++;
            }
        }
        memcpy(mem_ind, ind, sizeof (int) * (n + 1));
        toposort();

        int ans = INF;
        for (int i = 0; i < 3; i++)
        {
            int tmp = calc(i);
            if (tmp < ans)
                ans = tmp;
        }
        printf("%d\n", ans);
    }
    return 0;
}

/*
8
1 2 1 2 3 2 1 3
0
0
1 1
1 2
2 1 2
2 3 5
2 4 5
2 6 7
 */


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <numeric>
#include <functional>
#include <algorithm>

using namespace std;

const int N = 255;
const int INF = 0x3f3f3f3f;

bool mat[N][N];
int val[N];
int ind[N], mem_ind[N];
int topo[N];
int n;

void toposort()
{
    int front = 0, rear = 0;
    for (int i = 1; i <= n; i++)
        if (ind[i] == 0)
            topo[rear++] = i;
    while (front < rear)
    {
        int u = topo[front++];
        for (int i = 1; i <= n; i++)
        {
            if (mat[u][i])
            {
                ind[i]--;
                if (ind[i] == 0)
                    topo[rear++] = i;
            }
        }
    }
}

int calc(int pos)
{
    memcpy(ind, mem_ind, sizeof (int) * (n + 1));
    bool vis[N] = {};
    int rem = n, cost = 0;
    for (; rem; cost++)
    {
        for (int i = 0; i < n; i++)
        {
            int u = topo[i];
            if (!vis[u] && ind[u] == 0 && val[u] == pos)
            {
                cost++;
                rem--;
                for (int v = 1; v <= n; v++)
                    if (mat[u][v])
                        ind[v]--;
            }
        }

        pos++;
        if (pos == 3)    pos = 0;
    }
    return cost - 1;
}

int main()
{
    while (scanf("%d", &n) == 1)
    {
        memset(mat, 0, sizeof (mat));
        memset(ind, 0, sizeof (ind));
        for (int i = 1; i <= n; i++)
            scanf("%d", val + i), val[i]--;
        for (int i = 1; i <= n; i++)
        {
            int k, v;
            scanf("%d", &k);
            while (k--)
            {
                scanf("%d", &v);
                mat[v][i] = true;
                ind[i]++;
            }
        }
        memcpy(mem_ind, ind, sizeof (int) * (n + 1));
        toposort();

        int ans = INF;
        for (int i = 0; i < 3; i++)
        {
            int tmp = calc(i);
            if (tmp < ans)
                ans = tmp;
        }
        printf("%d\n", ans);
    }
    return 0;
}


#include <cstdio>
#include <cstring>
#include <cmath>
#include <cctype>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <numeric>
#include <functional>
#include <algorithm>

using namespace std;

const int N = 255;
const int INF = 0x3f3f3f3f;

bool mat[N][N];
int val[N];
int ind[N], mem_ind[N];
int topo[N];
int n;

void toposort()
{
    int front = 0, rear = 0;
    for (int i = 1; i <= n; i++)
        if (ind[i] == 0)
            topo[rear++] = i;
    while (front < rear)
    {
        int u = topo[front++];
        for (int i = 1; i <= n; i++)
        {
            if (mat[u][i])
            {
                ind[i]--;
                if (ind[i] == 0)
                    topo[rear++] = i;
            }
        }
    }
}

int calc(int pos)
{
    memcpy(ind, mem_ind, sizeof (int) * (n + 1));
    bool vis[N] = {};
    int rem = n, cost = 0;
    for (; rem; cost++)
    {
        for (int i = 0; i < n; i++)
        {
            int u = topo[i];
            if (!vis[u] && ind[u] == 0 && val[u] == pos)
            {
                cost++;
                rem--;
                for (int v = 1; v <= n; v++)
                    if (mat[u][v])
                        ind[v]--;
            }
        }

        pos++;
        if (pos == 3)    pos = 0;
    }
    return cost - 1;
}

int main()
{
    while (scanf("%d", &n) == 1)
    {
        memset(mat, 0, sizeof (mat));
        memset(ind, 0, sizeof (ind));
        for (int i = 1; i <= n; i++)
            scanf("%d", val + i), val[i]--;
        for (int i = 1; i <= n; i++)
        {
            int k, v;
            scanf("%d", &k);
            while (k--)
            {
                scanf("%d", &v);
                mat[i][v] = true;
                ind[v]++;
            }
        }
        memcpy(mem_ind, ind, sizeof (int) * (n + 1));
        toposort();

        int ans = INF;
        for (int i = 0; i < 3; i++)
        {
            int tmp = calc(i);
            if (tmp < ans)
                ans = tmp;
        }
        printf("%d\n", ans);
    }
    return 0;
}


#include<bits/stdc++.h>
#include<functional>
#include<string.h>
using namespace std;
#define ll   long long  int
#define mp make_pair
#define s second
#define f first
#define mod 1000000007
#define pi pair<ll,pair<ll,ll> >
#define pb push_back
#define INF 1000000
ll c[211];
ll n;
vector<ll>v[211];
ll vis[211];
bool allow(ll ind){
	for(int i=0;i<(int)v[ind].size();i++){
	if(vis[v[ind][i]]==0) return 0;
	}
	return 1;
}
ll check(ll s){
	s--;
	ll ans=0;
	ll marked=0;
	for(int i=0;i<211;i++) vis[i]=0;
	while(1){
		for(int i=1;i<=n;i++){
			if(c[i]==s+1 && allow(i) && !vis[i] ){
			vis[i]=1;
		    i=1;
			marked++;
			//break;
			}
		}
		ans++;
		s++;
		s%=3;
		if(marked==n)break;
	}
	ans--;
	return ans;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++) cin>>c[i];
	ll ans=INF;
	ll u;
	for(int i=1;i<=n;i++){
	ll k;
	cin>>k;
	for(int j=1;j<=k;j++){
	cin>>u;
	v[i].pb(u);
	}
	}
	for(int i=1;i<=3;i++) ans=min(ans,check(i));
	cout<<ans+n;
}


#include<bits/stdc++.h>
#include<functional>
#include<string.h>
using namespace std;
#define ll   long long  int
#define mp make_pair
#define s second
#define f first
#define mod 1000000007
#define pi pair<ll,pair<ll,ll> >
#define pb push_back
#define INF 1000000
ll c[211];
ll n;
vector<ll>v[211];
ll vis[211];
bool allow(ll ind){
	for(int i=0;i<(int)v[ind].size();i++){
	if(vis[v[ind][i]]==0) return 0;
	}
	return 1;
}
ll check(ll s){
	s--;
	ll ans=0;
	ll marked=0;
	for(int i=0;i<211;i++) vis[i]=0;
	while(1){
		for(int i=1;i<=n;i++){
			if(c[i]==s+1 && allow(i) && !vis[i] ){
			vis[i]=1;

		     i=0;
			marked++;

			}
		}
		s++;
		s%=3;
		if(marked==n)break;
		ans++;
	}
//	ans--;
	return ans;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++) cin>>c[i];
	ll ans=INF;
	ll u;
	for(int i=1;i<=n;i++){
	ll k;
	cin>>k;
	for(int j=1;j<=k;j++){
	cin>>u;
	v[i].pb(u);
	}
	}
	for(int i=1;i<=3;i++){ ans=min(ans,check(i));}
	cout<<ans+n;
}


#include<iostream>
#include<cstring>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<string>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int loc[210];
vector <int> V[3];
vector <int> G[210];
int d[210];
int d1[210];
bool book[210];
int n;
int count(int u){
	for(int i = 1;i<=n;i++)
		V[loc[i]-1].push_back(i);
	memcpy(d1,d,sizeof(d1));
	memset(book,0,sizeof(book));
	bool flag;
	int num = 0,ret = -1;
	while(num < n){
		ret++;
		flag = 1;
		while(flag){
			flag = 0;
			for(int i = 0;i<V[u].size();i++){
				int v = V[u][i];
				if(!book[v] && !d1[v]){
					num++;
					for(int j = 0;j<G[v].size();j++){
						int w = G[v][j];
						d1[w]--;
						flag = 1;
					}
					book[v] = 1;
				}
			}
		}
		u = (u + 1) % 3;
	}
	return ret + n;
}
int main(){
	int t,tmp;
	scanf("%d",&n);
	for(int i = 1;i<=n;i++){
		scanf("%d",&loc[i]);
	}
	for(int i = 1;i<=n;i++){
		scanf("%d",&d[i]);
		for(int j = 0;j<d[i];j++){
			scanf("%d",&tmp);
			G[tmp].push_back(i);
		}
	}
	int ans = 0x3f3f3f3f;
	for(int i = 0;i<3;i++)
		ans = min(ans,count(i));
	printf("%d\n",ans);
}


#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<queue>
#include<map>
#include<set>
#include<stack>
#include<bitset>
#include<numeric>
#include<vector>
#include<string>
#include<iterator>
#include<cstring>
#include<functional>
#define INF 0x3f3f3f3f
#define ms(a,b) memset(a,b,sizeof(a))
#define pi 3.14159265358979

using namespace std;

typedef pair<int, int> P;
typedef long long ll;
typedef unsigned long long ull;

int n, c[205], in[205];
vector<int> mp[205];

int bfs(int k)
{
	queue<int> q[5];
	for (int i = 1; i <= n; i++)
	{
		if (!in[i]) q[c[i]].push(i);
	}
	int iin[205], step = -1;
	for (int i = 1; i <= n; i++) iin[i] = in[i];
	while (q[1].size() || q[2].size() || q[3].size())
	{
		step++;
		while (q[k].size())
		{
			step++;
			int p = q[k].front(); q[k].pop();
			for (int i = 0; i < mp[p].size(); i++)
			{
				iin[mp[p][i]]--;
				if (!iin[mp[p][i]]) q[c[mp[p][i]]].push(mp[p][i]);
			}
		}
		if (k == 1) k = 2;
		else if (k == 2) k = 3;
		else k = 1;
	}
	if (step != -1) return step;
	else return 0;
}

int main()
{
	cin >> n;
	ms(in, 0);
	for (int i = 1; i <= n; i++)
	{
		cin >> c[i];
	}
	for (int i = 1; i <= n; i++)
	{
		int k;
		cin >> k;
		for (int j = 0; j < k; j++)
		{
			int p;
			cin >> p;
			mp[p].push_back(i);
			in[i]++;
		}
	}
	int count = INF;
	for (int i = 1; i <= 3; i++)
	{
		count=min(count,bfs(i));
	}
	cout << count << endl;
}


#include <map>
#include <set>
#include <stack>
#include <queue>
#include <bitset>
#include <math.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <iomanip>
//#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
const double eps=1e-6;
const int N=205;
const int MOD=1000;
const int M=1e9+7;
const int INF=0x3f3f3f3f;
const int mod=1000000007;
const double pi=acos(-1.0);
int n,m;
int a,b;
int ct[5][5];
int d[N],de[N];
int vis[N];
vector <int> mp[N];
vector <int> s[5];
int solve (int x)
{
	memset(vis,0,sizeof(vis));
	for (int i=1;i<=n;i++)
		de[i]=d[i];
	int res=n-1,cnt=0;
	int pos=x;
	while (cnt<n)
	{
		int f=0;
		while(f==0)
		{
			f=1;
			for (int i=0;i<s[pos].size();i++)
			{
				int e=s[pos][i];
				if (vis[e]==0 && de[e]==0)
				{
					cnt++;
					vis[e]=1;
					for (int j=0;j<mp[e].size();j++)
					{
						int p=mp[e][j];
						if (vis[p]==0)
						{
							de[p]--;
							f=0;
						}
					}
				}
			}
		}
			// for (int i=1;i<=n;i++)
			// 	cout<<de[i]<<" ";
			// cout<<endl;
		pos = (pos==3 ? 1 : pos+1);
		res++;
	}
	return res;
}
void ini()
{
	memset(mp,0,sizeof(mp));
	memset(d,0,sizeof(d));
	for (int i=0;i<4;i++)
		s[i].clear(),mp[i].clear();
}
int main()
{
	ct[1][2]=1,ct[1][3]=2;
	ct[2][1]=2,ct[2][3]=1;
	ct[3][1]=1,ct[3][2]=2;
	while (~scanf("%d",&n))
	{
		ini();
		for (int i=1;i<=n;i++)
			scanf("%d",&a),s[a].push_back(i);
		for (int i=1;i<=n;i++)
		{
			scanf("%d",&m);
			d[i]=m;
			for (int j=0;j<m;j++)
				scanf("%d",&a),mp[a].push_back(i);
		}
		int ans=INF;
		for (int i=1;i<=3;i++)
		{
			ans=min(ans,solve(i));
			// cout<<i<<" "<<ans<<endl;
		}
		printf("%d\n", ans);
	}
	return 0;
}
/*
5
2 2 1 1 3
1 5
2 5 1
2 5 4
1 5
0

1
1
0
*/


#include <cstdio>
#include <cstring>
#include <cstdlib>

int c[234], a[234][234], u[234];

int main (void)
{
  int n;
  while (scanf ("%d", &n) != EOF)
  {
    int i, j, l;
    int res = 200 * 200 * 200, tres;
    for (i = 1; i <= n; i++)
      scanf ("%d", &c[i]);
    for (i = 1; i <= n; i++)
    {
      scanf ("%d", &a[i][0]);
      for (j = 1; j <= a[i][0]; j++)
        scanf ("%d", &a[i][j]);
    }
    for (int s = 1; s <= 3; s++)
    {
      int t = s;
      tres = 0;
      l = 0;
      memset (u, 0, sizeof(u));
//      printf ("\nstart = %d\n", s);

      while (l < n)
      {
        for (i = 1; i <= n; i++)  if (c[i] == t && u[i] == 0)
        {
          for (j = 1; j <= a[i][0]; j++)
             if (u[a[i][j]] == 0 && c[a[i][j]] != t)
               break;
          if (j < a[i][0] + 1)
            continue;
          u[i] = 1;
          tres++;
//          printf ("%d ", i);
          l++;
        }
        if (l < n)
        {
          t++;
          if (t > 3)
            t = 1;
          tres++;
        }
      }
//      printf ("\ntres = %d\n", tres);
      if (res > tres)
        res = tres;
    }
    printf ("%d\n", res);
  }
  return 0;
}


#include <cstdio>
#include <cstring>
#include <cstdlib>

int c[234], a[234][234], u[234];

int main (void)
{
  int n;
  while (scanf ("%d", &n) != EOF)
  {
    int i, j, l;
    int res = 200 * 200 * 200, tres;
    for (i = 1; i <= n; i++)
      scanf ("%d", &c[i]);
    for (i = 1; i <= n; i++)
    {
      scanf ("%d", &a[i][0]);
      for (j = 1; j <= a[i][0]; j++)
        scanf ("%d", &a[i][j]);
    }
    for (int s = 1; s <= 3; s++)
    {
      int t = s;
      tres = 0;
      l = 0;
      memset (u, 0, sizeof(u));
//      printf ("\nstart = %d\n", s);

      while (l < n)
      {
        for (i = 1; i <= n; i++)  if (c[i] == t && u[i] == 0)
        {
          for (j = 1; j <= a[i][0]; j++)
             if (u[a[i][j]] == 0)
               break;
          if (j < a[i][0] + 1)
            continue;
          u[i] = 1;
          i = 1;
          tres++;
//          printf ("%d ", i);
          l++;
        }
        if (l < n)
        {
          t++;
          if (t > 3)
            t = 1;
          tres++;
        }
      }
//      printf ("\ntres = %d\n", tres);
      if (res > tres)
        res = tres;
    }
    printf ("%d\n", res);
  }
  return 0;
}


#include <cstdio>
#include <cstring>
#include <cstdlib>

int c[234], a[234][234], u[234];

int main (void)
{
  int n;
  while (scanf ("%d", &n) != EOF)
  {
    int i, j, l;
    int res = 200 * 200 * 200, tres;
    for (i = 1; i <= n; i++)
      scanf ("%d", &c[i]);
    for (i = 1; i <= n; i++)
    {
      scanf ("%d", &a[i][0]);
      for (j = 1; j <= a[i][0]; j++)
        scanf ("%d", &a[i][j]);
    }
    for (int s = 1; s <= 3; s++)
    {
      int t = s;
      tres = 0;
      l = 0;
      memset (u, 0, sizeof(u));
//      printf ("\nstart = %d\n", s);

      while (l < n)
      {
        for (i = 1; i <= n; i++)  if (c[i] == t && u[i] == 0)
        {
          for (j = 1; j <= a[i][0]; j++)
             if (u[a[i][j]] == 0)
               break;
          if (j < a[i][0] + 1)
            continue;
          u[i] = 1;
          i = 0;
          tres++;
//          printf ("%d ", i);
          l++;
        }
        if (l < n)
        {
          t++;
          if (t > 3)
            t = 1;
          tres++;
        }
      }
//      printf ("\ntres = %d\n", tres);
      if (res > tres)
        res = tres;
    }
    printf ("%d\n", res);
  }
  return 0;
}


using namespace std;

#include<ios>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<string>
#include<map>
#include<queue>
#include<stack>
#include<utility>
#include<cstdio>
#include<cstdlib>
#include<cassert>
#include<numeric>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<deque>

#define FILES
#undef FILES

#ifdef FILES
#include<fstream>
ifstream cin("date.in");
ofstream cout("date.out");
#else
#include<iostream>
#endif

#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define ALL(a) a.begin(),a.end()
#define p_b(a) push_back(a)
#define m_p(a,b) make_pair(a,b)
#define p_p(a,b) p_b(m_p(a,b))

typedef unsigned char uchar;
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vint;
typedef queue<int> qint;
typedef pair<int,int> pii;
typedef vector<pii> vpii;
typedef vector<string> vstr;
typedef queue<int> qint;
typedef map<string,int> mpstri;
typedef map<int,int> mpinti;
typedef map<string,string> mpstrs;
typedef map<string,vstr> mpstrvs;
const int INFI=(1<<30);
const ull INFL=(1LL<<62);

int main(){
    int n;
    int p[201],in[4][201]={};
    vint v[201];

    cin>>n;

    for(int i=1;i<=n;i++)
        cin>>p[i];

    for(int i=1;i<=n;i++){
        int k; cin>>k;
        for(int l=1;l<=k;l++){
            int x; cin>>x;
            v[x].p_b(i);
        }
        in[1][i]=in[2][i]=in[3][i]=k;
    }

    int s[4]={-1,-1,-1,-1};

    for(int l=1;l<=3;l++){
        int cr=l;

        qint q[4];
        for(int i=1;i<=n;i++)
            if(!in[l][i])
                q[p[i]].push(i);

        while(!q[1].empty() || !q[2].empty() || !q[3].empty()){
            s[l]++;
            while(!q[cr].empty()){
                s[l]++;
                int i=q[cr].front(); q[cr].pop();
                for(uint j=0;j<v[i].size();j++){
                    in[l][v[i][j]]--;
                    if(!in[l][v[i][j]])
                        q[p[v[i][j]]].push(v[i][j]);
                }
            }
            cr++;
            if(cr==4) cr=1;
        }
    }

    cout<<min3(s[1],s[2],s[3]);

    return 0;
}


using namespace std;

#include<ios>
#include<iomanip>
#include<cmath>
#include<algorithm>
#include<vector>
#include<set>
#include<string>
#include<map>
#include<queue>
#include<stack>
#include<utility>
#include<cstdio>
#include<cstdlib>
#include<cassert>
#include<numeric>
#include<cstring>
#include<sstream>
#include<algorithm>
#include<deque>

#define FILES
#undef FILES

#ifdef FILES
#include<fstream>
ifstream cin("date.in");
ofstream cout("date.out");
#else
#include<iostream>
#endif

#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define ALL(a) a.begin(),a.end()
#define p_b(a) push_back(a)
#define m_p(a,b) make_pair(a,b)
#define p_p(a,b) p_b(m_p(a,b))

typedef unsigned char uchar;
typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vint;
typedef queue<int> qint;
typedef pair<int,int> pii;
typedef vector<pii> vpii;
typedef vector<string> vstr;
typedef queue<int> qint;
typedef map<string,int> mpstri;
typedef map<int,int> mpinti;
typedef map<string,string> mpstrs;
typedef map<string,vstr> mpstrvs;
const int INFI=(1<<30);
const ull INFL=(1LL<<62);

int main(){
    int n;
    int p[201],in[201]={};
    vint v[201];

    cin>>n;

    for(int i=1;i<=n;i++)
        cin>>p[i];

    for(int i=1;i<=n;i++){
        int k; cin>>k;
        for(int l=1;l<=k;l++){
            int x; cin>>x;
            v[x].p_b(i);
        }
        in[i]=k;
    }

    qint q[4];
    for(int i=1;i<=n;i++)
        if(!in[i])
            q[p[i]].push(i);

    int s=-1,cr;

    for(int i=1;i<=3;i++)
        if(!q[i].empty()){
            cr=i;
            break;
        }

    while(!q[1].empty() || !q[2].empty() || !q[3].empty()){
        s++;
        while(!q[cr].empty()){
            s++;
            int i=q[cr].front(); q[cr].pop();
            for(uint j=0;j<v[i].size();j++){
                in[v[i][j]]--;
                if(!in[v[i][j]])
                    q[p[v[i][j]]].push(v[i][j]);
            }
        }
        cr++;
        if(cr==4) cr=1;
    }

    cout<<s;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <vector>
#include <cmath>
#include <map>
#include <set>

using namespace std;

const int MAX_N = 205;

int n;
int c[MAX_N];
int deg[MAX_N];
vector<int> r[MAX_N];
vector<int> g[MAX_N];

vector<int> q[4];

int main() {
    cin >> n;
    for (int i = 0; i < n; ++i) {
        scanf("%d", &c[i]);
        --c[i];
    }
    for (int i = 0; i < n; ++i) {
        int x; scanf("%d", &x);
        for (int j = 0; j < x; ++j) {
            int y; scanf("%d", &y);
            g[i].push_back(y - 1);
            r[y - 1].push_back(i);
        }
    }
    int res = 987654321;
    for (int sta_comp = 0; sta_comp <= 2; ++sta_comp) {
        memset(deg, 0, sizeof(deg));
        for (int i = 0; i < n; ++i)
            deg[i] = g[i].size();
        for (int i = 0; i < 3; ++i) q[i].clear();
        for (int i = 0; i < n; ++i)
           if (deg[i] == 0)
               q[c[i]].push_back(i);
        int cur_comp = sta_comp;
        int cur_res = 0;
        while (1) {
            bool end = true;
            for (int i = 0; i < 3; ++i)
                if (q[i].size() != 0)
                    end = false;
            if (end) break;
            if (q[cur_comp].size() == 0) {
                ++cur_res;
                cur_comp = (cur_comp + 1) % 3;
            } else {
                ++cur_res;
                int node = q[cur_comp][q[cur_comp].size() - 1];
                q[cur_comp].pop_back();
                for (int i = 0; i < r[node].size(); ++i) {
                    int nnode = r[node][i];
                    if (--deg[nnode] == 0)
                        q[c[nnode]].push_back(nnode);
                }
            }
        }
        res = min(res, cur_res);
    }
    cout << res << endl;
    return 0;
}


#define TASKNAME "text"

#include <cstdio>
#include <iostream>

#include <cmath>
#include <algorithm>
#include <functional>

#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>

#include <ctime>
#include <cassert>

#include <map>
#include <set>
#include <vector>

#define EPS 1e-9
#define INF int(1e9)
#define INFLONG (long long)(1e18)
#define sqr(a) ((a) * (a))
#define abs(a) (((a) < 0) ? -(a) : (a))
#define sz(a) (int)a.size()
#define all(a) (a).begin(), (a).end()
#define zero(a) memset(a, 0, sizeof(a))
#define fst first
#define snd second
#define y1 osrughosduvgarligybakrybrogvba
#define y0 aosfigdalrowgyalsouvgrlvygalri
#define mp make_pair
#define pb push_back
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#ifdef WIN32
  #define I64d "%I64d"
#else
  #define I64d "%lld"
#endif

using namespace std;

typedef long long ll;
typedef long double ld;
typedef vector <int> vi;
typedef vector <vi> vvi;
typedef vector <bool> vb;
typedef vector <vb> vvb;
typedef vector <ll> vl;
typedef vector <vl> vvl;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair <ll, int> pli;
typedef pair <int, ll> pil;
typedef vector <pii> vpii;

const int MaxN = 210;

int n;
int size[MaxN], c[MaxN];
int cnt[3];
vi gr[MaxN];
bool was[MaxN];

int main()
{
  #ifdef LocalHost
    freopen(TASKNAME".in", "r", stdin);
    freopen(TASKNAME".out", "w", stdout);
  #endif
  while (scanf("%d", &n) >= 1)
  {
    zero(cnt);
    for (int i = 0; i < n; i++)
      gr[i].clear();
    for (int i = 0; i < n; i++)
      scanf("%d", &c[i]), --c[i];
    vi now;
    for (int i = 0; i < n; i++)
    {
      int k, a;
      scanf("%d", &k);
      size[i] = k;
      if (!k)
        now.pb(i), cnt[c[i]]++;
      for (int j = 0; j < k; j++)
      {
        scanf("%d", &a);
        --a;
        gr[a].pb(i);
      }
    }

    zero(was);
    int ans = 0;
    int computer = INF;
    int t = 0;
    for (int i = 0; i < 3; i++)
      if (cnt[i])
        ++t;
    if (t == 3)
      computer = 0;
    if (t == 1)
      for (int i = 0; i < 3; i++)
        if (cnt[i])
         computer = i;
    if (t == 2)
      for (int i = 0; i < 3; i++)
        if (cnt[i] && cnt[(i + 1) % 3])
          computer = i;
    while (sz(now))
    {
      if (!cnt[computer])
        while (1)
        {
          computer = (computer + 1) % 3;
          ++ans;
          if (cnt[computer])
            break;
        }
      for (int i = 0; i < sz(now); i++)
      {
        if (c[now[i]] == computer)
        {
          was[now[i]] = 1;
          for (int j = 0; j < sz(gr[now[i]]); j++)
            size[gr[now[i]][j]]--;
          ++ans;
        }
        cnt[c[now[i]]]--;
      }
      vi new_now;
      for (int i = 0; i < n; i++)
        if (!was[i] && !size[i])
          new_now.pb(i), cnt[c[i]]++;
      now = new_now;
    }
    printf("%d\n", ans);
  }
  return 0;
}


#define TASKNAME "text"

#include <cstdio>
#include <iostream>

#include <cmath>
#include <algorithm>
#include <functional>

#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>

#include <ctime>
#include <cassert>

#include <map>
#include <set>
#include <vector>

#define EPS 1e-9
#define INF int(1e9)
#define INFLONG (long long)(1e18)
#define sqr(a) ((a) * (a))
#define abs(a) (((a) < 0) ? -(a) : (a))
#define sz(a) (int)a.size()
#define all(a) (a).begin(), (a).end()
#define zero(a) memset(a, 0, sizeof(a))
#define fst first
#define snd second
#define y1 osrughosduvgarligybakrybrogvba
#define y0 aosfigdalrowgyalsouvgrlvygalri
#define mp make_pair
#define pb push_back
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#ifdef WIN32
  #define I64d "%I64d"
#else
  #define I64d "%lld"
#endif

using namespace std;

typedef long long ll;
typedef long double ld;
typedef vector <int> vi;
typedef vector <vi> vvi;
typedef vector <bool> vb;
typedef vector <vb> vvb;
typedef vector <ll> vl;
typedef vector <vl> vvl;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair <ll, int> pli;
typedef pair <int, ll> pil;
typedef vector <pii> vpii;

const int MaxN = 210;

int n;
int size[MaxN], c[MaxN], ssize[MaxN];
int cnt[3], scnt[3];
vi gr[MaxN];
bool was[MaxN];

int main()
{
  #ifdef LocalHost
    freopen(TASKNAME".in", "r", stdin);
    freopen(TASKNAME".out", "w", stdout);
  #endif
  while (scanf("%d", &n) >= 1)
  {
    zero(scnt);
    for (int i = 0; i < n; i++)
      gr[i].clear();
    for (int i = 0; i < n; i++)
      scanf("%d", &c[i]), --c[i];
    vi snow;
    for (int i = 0; i < n; i++)
    {
      int k, a;
      scanf("%d", &k);
      ssize[i] = k;
      if (!k)
        snow.pb(i), scnt[c[i]]++;
      for (int j = 0; j < k; j++)
      {
        scanf("%d", &a);
        --a;
        gr[a].pb(i);
      }
    }

    int answer = INF;
    for (int scomputer = 0; scomputer < 3; scomputer++)
    {
      int computer = scomputer;
      int ans = 0;
      zero(was);
      vi now = snow;
      for (int i = 0; i < n; i++)
        size[i] = ssize[i];
      for (int i = 0; i < 3; i++)
        cnt[i] = scnt[i];
      while (sz(now))
      {
        if (!cnt[computer])
          while (1)
          {
            computer = (computer + 1) % 3;
            ++ans;
            if (cnt[computer])
              break;
          }
        for (int i = 0; i < sz(now); i++)
        {
          if (c[now[i]] == computer)
          {
            was[now[i]] = 1;
            for (int j = 0; j < sz(gr[now[i]]); j++)
              size[gr[now[i]][j]]--;
            ++ans;
          }
          cnt[c[now[i]]]--;
        }
        vi new_now;
        for (int i = 0; i < n; i++)
          if (!was[i] && !size[i])
            new_now.pb(i), cnt[c[i]]++;
        now = new_now;
      }
      answer = min(answer, ans);
    }
    printf("%d\n", answer);
  }
  return 0;
}


#define TASKNAME "text"

#include <cstdio>
#include <iostream>

#include <cmath>
#include <algorithm>
#include <functional>

#include <string>
#include <cstring>
#include <cctype>
#include <cstdlib>

#include <ctime>
#include <cassert>

#include <map>
#include <set>
#include <vector>

#define EPS 1e-9
#define INF int(1e9)
#define INFLONG (long long)(1e18)
#define sqr(a) ((a) * (a))
#define abs(a) (((a) < 0) ? -(a) : (a))
#define sz(a) (int)a.size()
#define all(a) (a).begin(), (a).end()
#define zero(a) memset(a, 0, sizeof(a))
#define fst first
#define snd second
#define y1 osrughosduvgarligybakrybrogvba
#define y0 aosfigdalrowgyalsouvgrlvygalri
#define mp make_pair
#define pb push_back
#define eprintf(...) fprintf(stderr, __VA_ARGS__)

#ifdef WIN32
  #define I64d "%I64d"
#else
  #define I64d "%lld"
#endif

using namespace std;

typedef long long ll;
typedef long double ld;
typedef vector <int> vi;
typedef vector <vi> vvi;
typedef vector <bool> vb;
typedef vector <vb> vvb;
typedef vector <ll> vl;
typedef vector <vl> vvl;
typedef pair <int, int> pii;
typedef pair <ll, ll> pll;
typedef pair <ll, int> pli;
typedef pair <int, ll> pil;
typedef vector <pii> vpii;

const int MaxN = 210;

int n;
int size[MaxN], c[MaxN];
int cnt[3];
vi gr[MaxN];
bool was[MaxN];

int main()
{
  #ifdef LocalHost
    freopen(TASKNAME".in", "r", stdin);
    freopen(TASKNAME".out", "w", stdout);
  #endif
  while (scanf("%d", &n) >= 1)
  {
    zero(cnt);
    for (int i = 0; i < n; i++)
      gr[i].clear();
    for (int i = 0; i < n; i++)
      scanf("%d", &c[i]), --c[i];
    vi now;
    for (int i = 0; i < n; i++)
    {
      int k, a;
      scanf("%d", &k);
      size[i] = k;
      if (!k)
        now.pb(i), cnt[c[i]]++;
      for (int j = 0; j < k; j++)
      {
        scanf("%d", &a);
        --a;
        gr[a].pb(i);
      }
    }
    zero(was);
    int ans = 0;
    int computer = INF;
    int t = 0;
    for (int i = 0; i < 3; i++)
      if (cnt[i])
        ++t;
    if (t == 3)
      computer = 0;
    if (t == 1)
      for (int i = 0; i < 3; i++)
        if (cnt[i])
         computer = i;
    if (t == 2)
      for (int i = 0; i < 3; i++)
        if (cnt[i] && cnt[(i + 1) % 3])
          computer = i;
    while (sz(now))
    {
      bool ok = 0;
      for (int i = 0; i < sz(now); i++)
        if (c[now[i]] == computer)
          ok = 1;
      if (!ok)
        while (1)
        {
          computer = (computer + 1) % 3;
          ++ans;
          bool ok = 0;
          for (int i = 0; i < sz(now); i++)
            if (c[now[i]] == computer)
              ok = 1;
          if (ok)
            break;
        }
      for (int i = 0; i < sz(now); i++)
      {
        if (c[now[i]] == computer)
        {
          was[now[i]] = 1;
          for (int j = 0; j < sz(gr[now[i]]); j++)
            size[gr[now[i]][j]]--;
          ++ans;
          cnt[c[now[i]]]--;
        }
      }
      vi new_now;
      for (int i = 0; i < n; i++)
        if (!was[i] && !size[i])
          new_now.pb(i), cnt[c[i]]++;
      now = new_now;
    }
    printf("%d\n", ans);
  }
  return 0;
}


#include<iostream>
#include<set>
#include<map>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<stdio.h>
#include<cmath>
#include<queue>
using namespace std;

bool gdbg = 0;

#define f(i,k,n) for(int i = k;i < n;i += 1)
#define DBG(s) if(gdbg)cout << s << endl;
#define W(x) while(x)
#define I(x) if(x)
#define Max 1000000009
#define pb push_back
#define sz(a) int((a).size())
#define vfi vector<float>::iterator
#define vsi vector<string>::iterator
#define vii vector<int>::iterator
#define vli vector<long long int>::iterator
#define sfi set<float>::iterator
#define sii set<int>::iterator
#define sli set<long long int>::iterator
#define ssi set<string>::iterator

typedef long long LL;
typedef long double LD;
typedef vector<int> VI;
typedef vector<string> VS;
typedef string str;
typedef char C;
typedef set<int> SI;
typedef set<string> SS;
typedef set<float> SF;
typedef set<long long int> SL;
typedef map<int,vector<int> > MII;

int main()
{
    int n;
    cin >> n;
    int H[n+1];
    int C[5][n+1];
    vector<vector<int> >A(n+1,vector<int>(n+1,0));
    f(i,1,n+1){cin >> H[i];}
    queue<int>Q;
    MII NA;
    f(i,1,n+1)
    {
              cin >> C[0][i];
              if(C[0][i] == 0)Q.push(i);
              f(j,1,5)C[j][i] = C[0][i];
              f(j,0,C[0][i])
              {
                   int k;
                   cin >> k;
                   A[i][k] = 1;
              }
    }
    while(!Q.empty())
    {
                     int x = Q.front();
                     Q.pop();
                     NA[H[x]].pb(x);
                     int k = NA[H[x]].size();
                     f(i,1,n+1)
                     {
                               if(A[i][x] == 1)
                               {
                                          C[4][i]--;
                                          if(C[4][i] == 0)Q.push(i);
                               }
                     }
    }
    long long int min = 100000000;
    f(i,1,4)
    {
              int j = i;
              int con = 0;
              long long int h = 0;
              vector<int>B(4,0);
              while(con < n)
              {
                     f(k,0,NA[j].size())
                     {
                           int t = NA[j][k];
                           if(C[i][t] == 0)
                           {
                                      C[i][t]--;
                                      con++;
                                      h++;
                                      f(l,1,n+1)
                                      {
                                                if(A[l][t] == 1)C[i][l]--;
                                      }
                           }
                     }
                     j = (j+1)%3;
                     if(j == 0)j = 3;
                     h = h+1;
              }
              if(min > h)min = h;
    }
    cout << min-1 << endl;
}


#include<iostream>
#include<set>
#include<map>
#include<vector>
#include<algorithm>
#include<cstdlib>
#include<stdio.h>
#include<cmath>
#include<queue>
using namespace std;

bool gdbg = 0;

#define f(i,k,n) for(int i = k;i < n;i += 1)
#define DBG(s) if(gdbg)cout << s << endl;
#define W(x) while(x)
#define I(x) if(x)
#define Max 1000000009
#define pb push_back
#define sz(a) int((a).size())
#define vfi vector<float>::iterator
#define vsi vector<string>::iterator
#define vii vector<int>::iterator
#define vli vector<long long int>::iterator
#define sfi set<float>::iterator
#define sii set<int>::iterator
#define sli set<long long int>::iterator
#define ssi set<string>::iterator

typedef long long LL;
typedef long double LD;
typedef vector<int> VI;
typedef vector<string> VS;
typedef string str;
typedef char C;
typedef set<int> SI;
typedef set<string> SS;
typedef set<float> SF;
typedef set<long long int> SL;
typedef map<int,vector<int> > MII;

int main()
{
    int n;
    cin >> n;
    int H[n+1];
    int C[5][n+1];
    vector<vector<int> >A(n+1,vector<int>(n+1,0));
    f(i,1,n+1){cin >> H[i];}
    queue<int>Q;
    MII NA;
    f(i,1,n+1)
    {
              cin >> C[0][i];
              if(C[0][i] == 0)Q.push(i);
              f(j,1,5)C[j][i] = C[0][i];
              f(j,0,C[0][i])
              {
                   int k;
                   cin >> k;
                   A[i][k] = 1;
              }
    }
    while(!Q.empty())
    {
                     int x = Q.front();
                     Q.pop();
                     NA[H[x]].pb(x);
                     f(i,1,n+1)
                     {
                               if(A[i][x] == 1)
                               {
                                          C[4][i]--;
                                          if(C[4][i] == 0)Q.push(i);
                               }
                     }
    }
    int min = 1000000;
    f(i,1,4)
    {
              int j = i;
              int con = 0;
              int h = 0;
              vector<int>B(4,0);
              while(con < n)
              {
                     //cout  << i << " " << con << endl;
                     f(k,B[j],NA[j].size())
                     {
                           int t = NA[j][k];
                           if(C[i][t] == 0)
                           {
                                      B[j]++;
                                      con++;
                                      h++;
                                      f(l,1,n+1)
                                      {
                                                if(A[l][t] == 1)C[i][l]--;
                                      }
                           }
                           else break;
                     }
                     j = (j+1)%3;
                     if(j == 0)j = 3;
                     h = h+1;
              }
              if(min > h)min = h;
    }
    cout << min-1 << endl;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
#include<string>

using namespace std;

int c[201];
vector<int> pre[201];
int n;

int solve(int current)
{
    bool mark[201] = {0};
    int cnt = 0,ans = 0;

    while(cnt < n)
    {
        for (int i=0;i<n;i++)
        {
            if (mark[i])
                continue;
            if (c[i] != current + 1)
                continue;

            bool all_pre_ok = true;
            for (int j=0;j<pre[i].size() && all_pre_ok;j++)
                if (!mark[pre[i][j]])
                    all_pre_ok = false;
            if (!all_pre_ok)
                continue;

            cnt++;
            mark[i] = 1;
            i = -1;
        }
        current++;
        current%=3;
        ans++;
    }

    return ans - 1;
}

int main()
{
    int a,b;
    cin>>n;
    for (int i=0;i<n;i++)
        cin>>c[i];
    for (int i=0;i<n;i++)
    {
        cin>>a;
        for (int j=0;j<a;j++)
        {
            cin>>b;
            pre[i].push_back(b-1);
        }
    }
    cout<<n + min(solve(0),min(solve(1),solve(2)))<<endl;
    return 0;
}


#include<iostream>
#include<vector>
#include<algorithm>
#include<fstream>
#include<string>

using namespace std;

int c[201];
vector<int> pre[201];
int n;

int solve(int current)
{
    bool mark[201] = {0};
    int cnt = 0,ans = 0;

    while(cnt < n)
    {
        for (int i=0;i<n;i++)
        {
            if (mark[i])
                continue;
            if (c[i] != current + 1)
                continue;

            bool all_pre_ok = true;
            for (int j=0;j<pre[i].size() && all_pre_ok;j++)
                if (!mark[pre[i][j]])
                    all_pre_ok = false;
            if (!all_pre_ok)
                continue;

            cnt++;
            mark[i] = 1;
            i = -1;
        }
        current++;
        current%=3;
        ans++;
    }

    return ans - 1;
}

int main()
{
    int a,b;
    cin>>n;
    for (int i=0;i<n;i++)
        cin>>c[i];
    for (int i=0;i<n;i++)
    {
        cin>>a;
        for (int j=0;j<a;j++)
        {
            cin>>b;
            pre[i].push_back(b-1);
        }
    }
    cout<<solve(0)<<" "<<solve(1)<<" "<<solve(2)<<endl;
    cout<<n + min(solve(0),min(solve(1),solve(2)))<<endl;
    return 0;
}


#include<iostream>
#include<cstring>
#include<cstdio>
#include<cstdlib>
#include<ctype.h>    //tower()
#include<set>
#include<map>
#include<iomanip>// cout<<setprecision(1)<<fixed<<a;
#include<vector>
#include<time.h>
#include<assert.h>  //assert
#include<cmath>
#include<algorithm>
#include<bitset>
#include<limits.h>
#include<stack>
#include<queue>
using namespace std;
const int maxn=100010;
const int maxm=1001;
const int inf=INT_MAX;

vector<int>itv[5],edge[205];
int Indegree[205],id[205],In[205];
int n,tmp,cnt,res;

int solve(int x)
{
	int res = 0;
	queue<int>que[5];
	for (int i = 1;i < 205;i++)
	{
		In[i] = Indegree[i];
	}
	for (int i = 1;i <= 3;i++)
	{
		for (int j = 0;j < itv[i].size();j++)
		{
			if (In[itv[i][j]] == 0)
			{
				que[i].push(itv[i][j]);
			}
		}
	}
	for (int i = x;;i = (i+1)%3)
	{
		if (i == 0) i = 3;
		while (!que[i].empty())
		{
			int val = que[i].front();
			que[i].pop();
			res++;
			for (int j = 0;j < edge[val].size();j++)
			{
				if (--In[edge[val][j]] == 0)
				{
					que[id[edge[val][j]]].push(edge[val][j]);
				}
			}
		}
		if (que[1].empty() && que[2].empty() && que[3].empty())	break;
		res++;
	}
	return res;
}

int main(){
	memset(Indegree,0,sizeof(Indegree));
	memset(id,0,sizeof(id));
	for (int i = 0;i < 5;i++) itv[i].clear();
	for (int i = 0;i < 205;i++) edge[i].clear();
	scanf("%d",&n);
	for (int i = 1;i <= n;i++){
		scanf("%d",&tmp);
		itv[tmp].push_back(i);
		id[i] = tmp;
	}
	for (int i = 1;i <= n;i++){
		scanf("%d",&cnt);
		while (cnt--){
			scanf("%d",&tmp);
			edge[tmp].push_back(i);
			Indegree[i]++;
		}
	}
	res = inf;
	for (int i = 1;i <= 3;i++){
		res = min(res,solve(i));
	}
	printf("%d\n",res);
	return 0;
}


#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
int n;
int c[205], k[205], kk[205];
bool g[205][205];
int check(int pos)
{
    int ans = n, r = n;
    memcpy(k, kk, sizeof k);
    while (r > 0) {
        for (int rep = 0; rep < n; ++rep)
            for (int i = 0; i < n; ++i) if (k[i] == 0 && c[i] == pos) {
                for (int j = 0; j < n; ++j) if (g[i][j]) k[j]--;
                k[i] = -1;
                r--;
            }
        if (r == 0) break;
        pos = (pos + 1) % 3; ++ans;
    }
    return ans;
}
int main()
{
    scanf("%d", &n);
    memset(g,0,sizeof(g));
    for (int i = 0; i < n; ++i) {
        scanf("%d", &c[i]); c[i]--;
    }
    int aij;
    for (int i = 0; i < n; ++i) {
        scanf("%d", &kk[i]);
        for (int j = 0; j < kk[i]; ++j) {
            scanf("%d", &aij);
            aij--;
            g[aij][i] = true;
        }
    }
    int ans = 0x7fffffff, cur;
    if ((cur = check(0)) < ans) ans = cur;
    if ((cur = check(1)) < ans) ans = cur;
    if ((cur = check(2)) < ans) ans = cur;
    for(int i=0;i<n;i++)
    {
        cout<<c[i]<<" ";
    }
    printf("%d\n", ans);
    return 0;
}


#include <string>
#include <cctype>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <cstring>
#include <stack>
#include <bitset>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <numeric>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <stack>
#include <functional>
#include <utility>
#include <iomanip>
#include <ctime>
using namespace std;
#define SZ(a) (int)(a).size()
#define FOR(i,a,b) for (int i=(a); i<=(b); ++i)
#define REP(i,n) for (int i=0; i<(n); ++i)
#define ALL(c) c.begin(), c.end()
#define CLR(c,n) memset(c,n,sizeof(c))
#define MCPY(d,s) memcpy(d,s,sizeof(s))
#define TR(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
#define CONTAIN(container, it) (container.find(it)!=container.end())
const int INF=0x3F3F3F3F;
template <class T> inline void checkmin(T& a, T b) {if (b<a) a=b;}
template <class T> inline void checkmax(T& a, T b) {if (b>a) a=b;}
typedef long long LL;
typedef vector<int> VI;
typedef vector<VI> VII;
typedef vector<string> VS;
typedef pair<int,int> PII;

int main(int argc, char** argv[]) {
#ifndef ONLINE_JUDGE
freopen("A.in", "r", stdin);
#endif
	int n, c[256], a, k[256], k2[256];
	bool v[256], g[256][256];
	cin>>n; FOR(i,1,n) cin>>c[i];
	CLR(g,0);
	FOR(i,1,n) {
		cin>>k[i];
		FOR(j,1,k[i]) {
			cin>>a;
			g[a][i]=true;
		}
	}
	int best=n*2;
	FOR(start,1,3) {
		CLR(v,0);
		MCPY(k2,k);
		a=start;
		int step=0;
		for (int left=n; left>0; a=a%3+1, ++step) {
			bool change=true;
			while (change) {
				change=false;
				FOR(i,1,n) if (!v[i]&&c[i]==a&&k2[i]==0) {
					cerr << i<< endl;
					v[i]=true;
					--left;
					change=true;
					FOR(j,1,n) if (g[i][j]) --k2[j];
				}
			}
		}
		checkmin(best, step+n-1);
	}
	cout << best << endl;
}


#include <string>
#include <cctype>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <cstring>
#include <stack>
#include <bitset>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <numeric>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <stack>
#include <functional>
#include <utility>
#include <iomanip>
#include <ctime>
using namespace std;
#define SZ(a) (int)(a).size()
#define FOR(i,a,b) for (int i=(a); i<=(b); ++i)
#define REP(i,n) for (int i=0; i<(n); ++i)
#define ALL(c) c.begin(), c.end()
#define CLR(c,n) memset(c,n,sizeof(c))
#define MCPY(d,s) memcpy(d,s,sizeof(s))
#define TR(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
#define CONTAIN(container, it) (container.find(it)!=container.end())
const int INF=0x3F3F3F3F;
template <class T> inline void checkmin(T& a, T b) {if (b<a) a=b;}
template <class T> inline void checkmax(T& a, T b) {if (b>a) a=b;}
typedef long long LL;
typedef vector<int> VI;
typedef vector<VI> VII;
typedef vector<string> VS;
typedef pair<int,int> PII;

int main(int argc, char** argv) {
#ifndef ONLINE_JUDGE
freopen("A.in", "r", stdin);
#endif
	int n, c[256], a, k[256], k2[256];
	bool v[256], g[256][256];
	cin>>n; FOR(i,1,n) cin>>c[i];
	CLR(g,0);
	FOR(i,1,n) {
		cin>>k[i];
		FOR(j,1,k[i]) {
			cin>>a;
			g[a][i]=true;
		}
	}
	int best=n*3;
	FOR(start,1,3) {
		CLR(v,0);
		MCPY(k2,k);
		a=start;
		int step=0;
		for (int left=n; left>0; a=a%3+1, ++step) {
			bool change=true;
			while (change) {
				change=false;
				FOR(i,1,n) if (!v[i]&&c[i]==a&&k2[i]==0) {
					v[i]=true;
					--left;
					change=true;
					FOR(j,1,n) if (g[i][j]) --k2[j];
				}
			}
		}
		checkmin(best, step+n-1);
	}
	cout << best << endl;
}


#include <string>
#include <cctype>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <cstring>
#include <stack>
#include <bitset>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <cmath>
#include <numeric>
#include <cstdlib>
#include <cstdio>
#include <queue>
#include <stack>
#include <functional>
#include <utility>
#include <iomanip>
#include <ctime>
using namespace std;
#define SZ(a) (int)(a).size()
#define FOR(i,a,b) for (int i=(a); i<=(b); ++i)
#define REP(i,n) for (int i=0; i<(n); ++i)
#define ALL(c) c.begin(), c.end()
#define CLR(c,n) memset(c,n,sizeof(c))
#define MCPY(d,s) memcpy(d,s,sizeof(s))
#define TR(container, it) for(typeof(container.begin()) it = container.begin(); it != container.end(); it++)
#define CONTAIN(container, it) (container.find(it)!=container.end())
const int INF=0x3F3F3F3F;
template <class T> inline void checkmin(T& a, T b) {if (b<a) a=b;}
template <class T> inline void checkmax(T& a, T b) {if (b>a) a=b;}
typedef long long LL;
typedef vector<int> VI;
typedef vector<VI> VII;
typedef vector<string> VS;
typedef pair<int,int> PII;

int main(int argc, char** argv[]) {
#ifndef ONLINE_JUDGE
freopen("A.in", "r", stdin);
#endif
	int n, c[256], a, k[256], k2[256];
	bool v[256], g[256][256];
	cin>>n; FOR(i,1,n) cin>>c[i];
	CLR(g,0);
	FOR(i,1,n) {
		cin>>k[i];
		FOR(j,1,k[i]) {
			cin>>a;
			g[a][i]=true;
		}
	}
	int best=n*2;
	FOR(start,1,3) {
		CLR(v,0);
		MCPY(k2,k);
		a=start;
		int step=0;
		for (int left=n; left>0; a=a%3+1, ++step) {
			bool change=true;
			while (change) {
				change=false;
				FOR(i,1,n) if (!v[i]&&c[i]==a&&k2[i]==0) {
					v[i]=true;
					--left;
					change=true;
					FOR(j,1,n) if (g[i][j]) --k2[j];
				}
			}
		}
		checkmin(best, step+n-1);
	}
	cout << best << endl;
}


#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define MP(a, b) make_pair(a, b)

const int maxn = 605, MAXV = maxn, MAXE = maxn * maxn;
int n, n1, n2, rule, disk[maxn];
int degree[maxn];

int ent[MAXV], ver[MAXE], nxt[MAXE], ENUM;
void addEdge(int u, int v) {
	ver[ENUM] = v;	nxt[ENUM] = ent[u];	ent[u] = ENUM++;
}

int optimal(int disk) {
	if (disk == 0) return 1;
	if (disk == 1) return 2;
	return 0;
}

int que[3][maxn], qL[3], qR[3], tDeg[maxn];	//<<
int TopoSort(int sta) {
	int ret = 0;
    qL[0] = qR[0] = qL[1] = qR[1] = qL[2] = qR[2] = 0;
    for (int i = 0; i < n; i++) {
        tDeg[i] = degree[i];
        if (tDeg[i] == 0)
            que[disk[i]][qR[disk[i]]++] = i;
    }
    int cur = sta;
    while (qL[cur] < qR[cur]) {
        while (qL[cur] < qR[cur]) {
            int u = que[cur][qL[cur]++], v;
			for (int i = ent[u]; ~i; i = nxt[i])
            if ((--tDeg[v = ver[i]]) == 0)
                que[disk[v]][qR[disk[v]]++] = v;
        }
		int nxt = optimal(cur);
		if (qL[nxt] < qR[nxt]) {
			ret += 1; cur = nxt;
		} else if (qL[3 - cur - nxt] < qR[3 - cur - nxt]) {
			ret += 2;	cur = 3 - cur - nxt;
		} else if (qR[0] + qR[1] + qR[2] == n)
			break;
		else
			return maxn;
    }
    if (qR[0] + qR[1] + qR[2] == n)
        return ret;
    return maxn;
}

int main() {
	while (cin >> n) {
		memset(ent, -1, sizeof(ent));	ENUM = 0;
		for (int i = 0; i < n; i++) {
			int t;	cin >> t;
			disk[i] = t - 1;
		}
		memset(degree, 0, sizeof(degree));
		for (int i = 0; i < n; i++) {
			int num, j;	cin >> num;
			while (num--) {
				cin >> j;	j--;
				addEdge(j, i);
				degree[i]++;
			}
		}
		int res = maxn;
		for (int i = 0; i < 3; i++) {
			int t = TopoSort(i);
			res = min(res, t);
		}
		cout << res + n << endl;
	}
	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define MP(a, b) make_pair(a, b)

const int maxn = 205, MAXV = maxn, MAXE = maxn * maxn;
int n, n1, n2, rule, disk[maxn];
int degree[maxn];

int ent[MAXV], ver[MAXE], nxt[MAXE], ENUM;
void addEdge(int u, int v) {
	ver[ENUM] = v;	nxt[ENUM] = ent[u];	ent[u] = ENUM++;
}

int optimal(int disk) {
	if (disk == 0) return 1;
	if (disk == 1) return 2;
	return 0;
}

int que[3][maxn], qL[3], qR[3], tDeg[maxn];	//<<
int TopoSort(int sta) {
	int ret = 0;
    qL[0] = qR[0] = qL[1] = qR[1] = qL[2] = qR[2] = 0;
    for (int i = 0; i < n; i++) {
        tDeg[i] = degree[i];
        if (tDeg[i] == 0)
            que[disk[i]][qR[disk[i]]++] = i;
    }
    int cur = sta;
    while (qL[cur] < qR[cur]) {
        while (qL[cur] < qR[cur]) {
            int u = que[cur][qL[cur]++], v;
			for (int i = ent[u]; ~i; i = nxt[i])
            if ((--tDeg[v = ver[i]]) == 0)
                que[disk[v]][qR[disk[v]]++] = v;
        }
		if (qR[0] + qR[1] + qR[2] == n)
			break;
		int nxt = optimal(cur);
		if (qL[nxt] < qR[nxt]) {
			ret += 1; cur = nxt;
		} else {
			ret += 2;	cur = 3 - cur - nxt;
		}
    }
    if (qR[0] + qR[1] + qR[2] == n)
        return ret;
    return maxn;
}

int main() {
	while (cin >> n) {
		memset(ent, -1, sizeof(ent));	ENUM = 0;
		for (int i = 0; i < n; i++) {
			int t;	cin >> t;
			disk[i] = t - 1;
		}
		memset(degree, 0, sizeof(degree));
		for (int i = 0; i < n; i++) {
			int num, j;	cin >> num;
			while (num--) {
				cin >> j;	j--;
				addEdge(j, i);
				degree[i]++;
			}
		}
		int res = maxn;
		for (int i = 0; i < 3; i++) {
			int t = TopoSort(i);
			res = min(res, t);
		}
		cout << res + n << endl;
	}
	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define MP(a, b) make_pair(a, b)

const int maxn = 605, MAXV = maxn, MAXE = maxn * maxn;
int n, n1, n2, rule, disk[maxn];
int degree[maxn];

int ent[MAXV], ver[MAXE], nxt[MAXE], ENUM;
void addEdge(int u, int v) {
	ver[ENUM] = v;	nxt[ENUM] = ent[u];	ent[u] = ENUM++;
}

int optimal(int disk) {
	if (disk == 0) return 1;
	if (disk == 1) return 2;
	return 0;
}

int que[3][maxn], qL[3], qR[3], tDeg[maxn];	//<<
int TopoSort(int sta) {
	int ret = 0;
    qL[0] = qR[0] = qL[1] = qR[1] = qL[2] = qR[2] = 0;
    for (int i = 0; i < n; i++) {
        tDeg[i] = degree[i];
        if (tDeg[i] == 0)
            que[disk[i]][qR[disk[i]]++] = i;
    }
    int cur = sta;
    while (qL[cur] < qR[cur]) {
        while (qL[cur] < qR[cur]) {
            int u = que[cur][qL[cur]++], v;
			for (int i = ent[u]; ~i; i = nxt[i])
            if ((--tDeg[v = ver[i]]) == 0)
                que[disk[v]][qR[disk[v]]++] = v;
        }
		if (qR[0] + qR[1] + qR[2] == n)
			break;
		int nxt = optimal(cur);
		if (qL[nxt] < qR[nxt]) {
			ret += 1; cur = nxt;
		} else if (qL[3 - cur - nxt] < qR[3 - cur - nxt]) {
			ret += 2;	cur = 3 - cur - nxt;
		} else
			return maxn;
    }
    if (qR[0] + qR[1] + qR[2] == n)
        return ret;
    return maxn;
}

int main() {
	while (cin >> n) {
		memset(ent, -1, sizeof(ent));	ENUM = 0;
		for (int i = 0; i < n; i++) {
			int t;	cin >> t;
			disk[i] = t - 1;
		}
		memset(degree, 0, sizeof(degree));
		for (int i = 0; i < n; i++) {
			int num, j;	cin >> num;
			while (num--) {
				cin >> j;	j--;
				addEdge(j, i);
				degree[i]++;
			}
		}
		int res = maxn;
		for (int i = 0; i < 3; i++) {
			int t = TopoSort(i);
			res = min(res, t);
		}
		cout << res + n << endl;
	}
	return 0;
}


#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
#define MP(a, b) make_pair(a, b)

const int maxn = 605, MAXV = maxn, MAXE = maxn * maxn;
int n, n1, n2, rule, disk[maxn];
int degree[maxn];

int ent[MAXV], ver[MAXE], nxt[MAXE], ENUM;
void addEdge(int u, int v) {
	ver[ENUM] = v;	nxt[ENUM] = ent[u];	ent[u] = ENUM++;
}

int optimal(int disk) {
	if (disk == 0) return 1;
	if (disk == 1) return 2;
	return 0;
}

int que[3][maxn], qL[3], qR[3], tDeg[maxn];	//<<
int TopoSort(int sta) {
	int ret = 0;
    qL[0] = qR[0] = qL[1] = qR[1] = qL[2] = qR[2] = 0;
    for (int i = 0; i < n; i++) {
        tDeg[i] = degree[i];
        if (tDeg[i] == 0)
            que[disk[i]][qR[disk[i]]++] = i;
    }
    int cur = sta;
    while (qL[cur] < qR[cur]) {
        while (qL[cur] < qR[cur]) {
            int u = que[cur][qL[cur]++], v;
			for (int i = ent[u]; ~i; i = nxt[i])
            if ((--tDeg[v = ver[i]]) == 0)
                que[disk[v]][qR[disk[v]]++] = v;
        }
		int nxt = optimal(cur);
		if (qL[nxt] < qR[nxt]) {
			ret += 1; cur = nxt;
		} else if (qL[3 - cur - nxt] < qR[3 - cur - nxt]) {
			ret += 2;	cur = 3 - cur - nxt;
		} else if (qR[0] + qR[1] + qR[2] == n)
			break;
		else
			return maxn;
    }
    if (qL[0] == qR[0] && qL[1] == qR[1] && qL[2] == qR[2] && qR[0] + qR[1] + qR[2] == n)
        return ret;
    return maxn;
}

int main() {
	while (cin >> n) {
		memset(ent, -1, sizeof(ent));	ENUM = 0;
		for (int i = 0; i < n; i++) {
			int t;	cin >> t;
			disk[i] = t - 1;
		}
		memset(degree, 0, sizeof(degree));
		for (int i = 0; i < n; i++) {
			int num, j;	cin >> num;
			while (num--) {
				cin >> j;	j--;
				addEdge(j, i);
				degree[i]++;
			}
		}
		int res = maxn;
		for (int i = 0; i < 3; i++) {
			int t = TopoSort(i);
			res = min(res, t);
		}
		cout << res + n << endl;
	}
	return 0;
}


#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;

vector<int> adj[200];
int comp[200];
int par[200];
vector<int> q;
vector<int> q2;
int cur;
int dist(int i, int j)
{
    if ((comp[j] - comp[i] == 1) || (comp[j] == 0 && comp[i] == 2))
        return 1;
    if (comp[j] - comp[i] == 0)
        return 0;
    return 2;
}

bool compr(int i, int j)
{
    return dist(cur, i) > dist(cur, j);
}

int main()
{
    int n,k,c;
    cin>>n;
    for (int i = 0; i <n; i++)
    {
        cin>>c;
        c--;
        comp[i] = c;
    }
    for (int i = 0; i <n; i++)
    {
        cin>>k;
        if (k == 0)
        {
            q.push_back(i);
            q2.push_back(i);
        }
        for (int j = 0; j < k; j++)
        {
            cin>>c;
            c--;
            adj[c].push_back(i);
            par[i]++;
        }
    }
    int sum = 0;
    int cmax = INT_MAX;
    for (int t = 0; t < q2.size(); t++)
    {
        sum = 0;
        while(!q.empty())
        {
            sum++;
            cur = q[q.size()-1];
        //  cout<<"cur: "<<cur;
            q.pop_back();
            for (int i = 0; i < adj[cur].size(); i++)
            {
                par[adj[cur][i]]--;
                if (par[adj[cur][i]] == 0)
                    q.push_back(adj[cur][i]);
            }
            if (!q.empty())
            {
                sort(q.begin(),q.end(), compr);
                sum += dist(cur, q[q.size()-1]);
            }
        //  cout<<"sum: "<<sum<<endl;
        }
        for (int k = t+1; k < q2.size(); k++)
            q.push_back(q2[k]);
        for (int k = 0; k < t+1; k++)
            q.push_back(q2[k]);
        cmax = min(cmax, sum);
    }
    cout<<cmax<<endl;
}


#include <iostream>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;

vector<int> adj[200];
int comp[200];
int par[200];
int par2[200];
vector<int> q;
vector<int> q2;
int cur;
int dist(int i, int j)
{
    if ((comp[j] - comp[i] == 1) || (comp[j] == 0 && comp[i] == 2))
        return 1;
    if (comp[j] - comp[i] == 0)
        return 0;
    return 2;
}

bool compr(int i, int j)
{
    return dist(cur, i) > dist(cur, j);
}

int main()
{
    int n,k,c;
    cin>>n;
    for (int i = 0; i <n; i++)
    {
        cin>>c;
        c--;
        comp[i] = c;
    }
    for (int i = 0; i <n; i++)
    {
        cin>>k;
        if (k == 0)
        {
            q.push_back(i);
            q2.push_back(i);
            par[i] = 0;
            par2[i] = 0;
        }
        for (int j = 0; j < k; j++)
        {
            cin>>c;
            c--;
            adj[c].push_back(i);
            par2[i]++;
            par[i]++;
        }
    }
    int sum = 0;
    int cmax = INT_MAX;
    for (int t = 0; t < q2.size(); t++)
    {
        sum = 0;
        while(!q.empty())
        {
            sum++;
            cur = q[q.size()-1];
        //  cout<<"cur: "<<cur;
            q.pop_back();
            for (int i = 0; i < adj[cur].size(); i++)
            {
                par[adj[cur][i]]--;
                if (par[adj[cur][i]] == 0)
                    q.push_back(adj[cur][i]);
            }
            if (!q.empty())
            {
                sort(q.begin(),q.end(), compr);
                sum += dist(cur, q[q.size()-1]);
            }
        //  cout<<"sum: "<<sum<<endl;
        }
        for (int k = t+1; k < q2.size(); k++)
            q.push_back(q2[k]);
        for (int k = 0; k < t+1; k++)
            q.push_back(q2[k]);
        for (int i = 0; i < n; i++)
            par[i] = par2[i];
        cmax = min(cmax, sum);
    }
    cout<<cmax<<endl;
}


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

void solve(){
    int n;
    cin >> n;
    char s[1010];
    scanf("%s",s+1);
    int ans = 0;
    for(int i = 1;i<=n;i++){
        if(s[i]=='1'){
            ans = max(ans,max(2*i,2*(n-i+1)));
        }
    }
    cout << ans << endl;
}

int main(){
    //freopen("in.txt","r",stdin);
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

void solve(){
    int n;
    cin >> n;
    char s[1010];
    scanf("%s",s+1);
    int ans = n;
    for(int i = 1;i<=n;i++){
        if(s[i]=='1'){
            ans = max(ans,max(2*i,2*(n-i+1)));
        }
    }
    cout << ans << endl;
}

int main(){
    //freopen("in.txt","r",stdin);
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

void solve(){
    int n;
    cin >> n;
    string s;
    cin >> s;
    int sum = 0;
    if(s[0]=='1' || s[n-1]=='1') cout << 2*n << endl;
    else {
        int i = 0,j=n-1;
        while(s[i]!='1' && i<n-1) i++;
        while(s[j]!='1'&& j>0) j--;
        if(i==n-1 && j==0) cout << n << endl;
        else {
            i++;j++;
            i = max(2*i,2*(n-i));
            j = max(2*j,2*(n-j));
            cout << max(i,j) << endl;
        }

    }
}

int main(){
    //freopen("in.txt","r",stdin);
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

void solve(){
    int n;
    cin >> n;
    string s;
    cin >> s;
    int sum = 0;
    if(s[0]=='1' || s[n-1]=='1') cout << 2*n << endl;
    else {
        int i = 0,j=n-1;
        while(s[i]!='1' && i<=j) i++;
        while(s[j]!='1'&& j>=i) j--;
        if(i>j) cout << n << endl;
        else if(i==j){
            if(n%2==1) i++;
            cout << max(2*i,2*(n-i)) << endl;
        }else {
            i = max(2*i,2*(n-i));
            j = max(2*j,2*(n-j));
            cout << max(i,j) << endl;
        }

    }
}

int main(){
    //freopen("in.txt","r",stdin);
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}


#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <string>

using namespace std;

void solve(){
    int n;
    cin >> n;
    string s;
    cin >> s;
    int sum = 0;
    if(s[0]=='1' || s[n-1]=='1') cout << 2*n << endl;
    else {
        int i = 0,j=n-1;
        while(s[i]!='1' && i<n-1) i++;
        while(s[j]!='1'&& j>0) j--;
        if(i==n-1 && j==0) cout << n << endl;
        else {

            i = max(2*i,2*(n-i));
            j = max(2*j,2*(n-j));
            cout << max(i,j)+(n%2==0?0:2) << endl;
        }

    }
}

int main(){
    freopen("in.txt","r",stdin);
    int t;
    cin >> t;
    while(t--){
        solve();
    }
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<cstdlib>
#include<cctype>
#include<cmath>

#define ll long long
#define I inline

using namespace std;

ll t;
ll len;
ll ans;
string s;
bool a[10001];

int main(){
    cin >> t;
    for(int i = 1; i <= t; i ++){
        cin >> len;
        cin >> s;
        for(int j = 1; j <= len; j ++){
            a[j] = (int )s[j - 1] - '0';
        }
        ans = len;
        for(int j = 1; j <= len; j ++){
            if(a[j] == 1){
                ans = max(ans , 2 * (len - j + 1));
            }
        }
        cout << ans << "\n";
    }
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<cstdlib>
#include<cctype>
#include<cmath>

#define ll long long
#define I inline

using namespace std;

ll t;
ll len;
ll ans;
string s;

int main(){
    cin >> t;
    for(int i = 1; i <= t; i ++){
        cin >> len;
        cin >> s;
        ans = len;
        for(int j = 0; j < len; j ++){
            if(s[j] == '1'){
                ans = max(ans , 2 * (len - j - 1 + 1));
            }
        }
        cout << ans << "\n";
    }
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<cstdlib>
#include<cctype>
#include<cmath>

#define ll long long
#define I inline

using namespace std;

ll t;
ll len;
ll ans;
string s;
bool a[10001];

int main(){
    cin >> t;
    for(int i = 1; i <= t; i ++){
        cin >> len;
        cin >> s;
        for(int i = 1; i <= len; i ++){
            a[i] = s[i - 1] - '0';
        }
        ans = len;
        for(int j = 1; j <= len; j ++){
            if(a[j] == '1'){
                ans = max(ans , 2 * (len - j + 1));
            }
        }
        cout << ans << "\n";
    }
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<cstdlib>
#include<cctype>
#include<cmath>

#define ll long long
#define I inline

using namespace std;

ll t;
ll len;
ll ans;
string s;
bool a[10001];

int main(){
    cin >> t;
    for(int i = 1; i <= t; i ++){
        cin >> len;
        cin >> s;
        for(int i = 1; i <= len; i ++){
            a[i] = s[i - 1] - '0';
        }
        ans = len;
        for(ll j = 1; j <= len; j ++){
            if(a[j] == 1){
                ans = max(ans , max(2 * (len - j + 1) , 2 * j));
            }
        }
        cout << ans << "\n";
    }
    return 0;
}


#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<queue>
#include<deque>
#include<vector>
#include<algorithm>
#include<iomanip>
#include<cstdlib>
#include<cctype>
#include<cmath>

#define ll long long
#define I inline

using namespace std;

ll t;
ll len;
ll ans;
string s;

int main(){
    cin >> t;
    for(int i = 1; i <= t; i ++){
        cin >> len;
        cin >> s;
        ans = len;
        for(int j = 0; j < len; j ++){
            if(s[j] == '1'){
                ans = max(ans , 2 * (len - j - 1 + 1));
            }
        }
        cout << ans << "\n";
        ans = 0;
    }
    return 0;
}


#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <climits>

using namespace std;

#define ll long long

int n;

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        int lateststair=0, early=n;
        bool notin=false;
        int stairs=0;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            char c;
            cin>>c;
            if(c=='1')
            {
                if(!notin)
                {
                    early=i;
                    notin=true;
                }
                lateststair=i+1;
                stairs++;
            }
        }
        //cout<<lateststair<<endl;

        if(stairs==0)
        {
            cout<<n<<endl;
        }
        else
        {
            cout<<max(lateststair*2, (n-early)*2)<<endl;
        }
        //cout<<2*(n-<<endl;

    }
}


#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <climits>

using namespace std;

#define ll long long

int n;
//bool vis [2][1001]={{0}};
bool staircase[1001]={0};

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        bool all=false;
        int stairs=0;
        cin>>n;
        for(int i=0;i<n;i++)
        {
            char c;
            cin>>c;
            if(c=='1')
            {
                if(i==0||i==n-1)
                {
                    all=true;
                }
                staircase[i]=true;
                stairs++;
            }
            else
            {
                staircase[i]=false;
            }
        }
        if(all)
        {
            cout<<n*2<<endl;
            continue;
        }
        if(stairs==0)
        {
            cout<<n<<endl;
        }
        else
        {
            cout<<n+1<<endl;
        }

    }
}


#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <climits>

using namespace std;

#define ll long long

int n;
//bool vis [2][1001]={{0}};
bool staircase[1001]={0};
vector<int>v;

void dfs(int floor, int node, int ans, bool vis[2][1001])
{

    vis[floor][node]=true;
    if(node>0&&!vis[floor][node-1])
    {
        dfs(floor, node-1, ans+1, vis);
    }
    if(node<n-1&&!vis[floor][node+1])
    {
        dfs(floor, node+1, ans+1, vis);
    }
    if(staircase[node])
    {
        if(floor==0&&!vis[1][node])
        {
            dfs(1, node, ans+1, vis);
        }
        if(floor==1&&!vis[0][node])
        {
            dfs(0, node, ans+1, vis);
        }
    }

    v.push_back(ans);
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        v.clear();
        cin>>n;
        for(int i=0;i<n;i++)
        {
            char c;
            cin>>c;
            if(c=='1')
            {
                staircase[i]=true;
            }
            else
            {
                staircase[i]=false;
            }
        }

       // dfs(0, 0, 1);
       // cout<<*max_element(v.begin(), v.end())<<endl;
        int ans=0;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<2;j++)
            {
                bool vis[2][1001]={{0}};
                dfs(j, i, 1, vis);
                ans=max(ans, *max_element(v.begin(), v.end()));
                v.clear();
                for(int k=0;k<n;k++)
                {
                    vis[0][k]=false;
                    vis[1][k]=false;
                }

            }
        }
        cout<<ans<<endl;

    }
}


#include<iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <cmath>
#include <queue>
#include <set>
#include <climits>

using namespace std;

#define ll long long

int n;
bool vis [2][1001]={{0}};
bool staircase[1001]={0};
vector<int>v;

void dfs(int floor, int node, int ans)
{

    vis[floor][node]=true;
    if(node>0&&!vis[floor][node-1])
    {
        dfs(floor, node-1, ans+1);
    }
    if(node<n-1&&!vis[floor][node+1])
    {
        dfs(floor, node+1, ans+1);
    }
    if(staircase[node])
    {
        if(floor==0&&!vis[1][node])
        {
            dfs(1, node, ans+1);
        }
        if(floor==1&&!vis[0][node])
        {
            dfs(0, node, ans+1);
        }
    }

    v.push_back(ans);
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        v.clear();
        cin>>n;
        for(int i=0;i<n;i++)
        {
            vis[0][i]=false;
            vis[1][i]=false;
            char c;
            cin>>c;
            if(c=='1')
            {
                staircase[i]=true;
            }
            else
            {
                staircase[i]=false;
            }
        }

       // dfs(0, 0, 1);
       // cout<<*max_element(v.begin(), v.end())<<endl;
        int ans=0;
        for(int i=0;i<n;i++)
        {
            for(int j=0;j<2;j++)
            {
                dfs(j, i, 1);
                ans=max(ans, *max_element(v.begin(), v.end()));
                v.clear();
                for(int k=0;k<n;k++)
                {
                    vis[0][k]=false;
                    vis[1][k]=false;
                }

            }
        }
        cout<<ans<<endl;

    }
}


#include<bits/stdc++.h>
using namespace std;
int main(){
         long  n,t;
         string s;
         cin>>t;
         while(t--){
         long  dem=0;
         long k=0;
         cin>>n>>s;
         for(long i=0;i<n;i++){
                  if(s[i]=='1'){
                           k=max(k,max(i+1,n-i));
                  }else dem++;
         }

         if(s[0]=='1'||s[n-1]=='1') cout<<2*n<<'\n';
         else if(2*k>dem) cout<<2*k<<'\n';else cout<<dem<<'\n';
         }
}


#include<bits/stdc++.h>
using namespace std;
int main(){
         long n,t;
         string s;
         cin>>t;
         while(t--){
         long dem=0;
         cin>>n;
         cin>>s;
         for(long i=0;i<s.length();i++){
                  if(s[i]=='0') dem++;
                  else dem+=2;
         }
         if(s[0]=='1'||s[s.length()-1]=='1') cout<<2*n<<'\n';else
         cout<<dem<<'\n';
         }
}


#include<bits/stdc++.h>
using namespace std;
int main(){
         long long n,t;
         string s;
         cin>>t;
         while(t--){
         long long dem=0;
         cin>>n;
         cin>>s;
         for(long i=0;i<n;i++){
                  if(s[i]=='0') dem++;
                  else dem+=2;
         }
         if(s[0]=='1'||s[n-1]=='1') cout<<2*n<<'\n';else
         cout<<dem<<'\n';
         }
}


#include<bits/stdc++.h>
using namespace std;
int main(){
         long  n,t;
         string s;
         cin>>t;
         while(t--){
         long  dem=0;
         long k=0;
         long count=0;
         cin>>n;
         cin>>s;
         for(long i=0;i<n;i++){
                  if(s[i]=='1'){
                           k=max(k,max(i+1,n-i-1));
                  }else dem++;
         }
         if(s[0]=='1'||s[n-1]=='1') cout<<2*n<<'\n';
         else if(2*k>dem) cout<<2*k<<'\n';else cout<<dem<<'\n';
         }
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  int n;
  vector<int> pos;
  string str;
  cin >> n;
  int sum = n;
  cin >> str;
  for(int i=0;i<n;i++){
    if(str[i] == '1'){
      pos.push_back(i+1);
    }
  }
  if(pos.size() > 0){
    sum += pos.size();
    if(pos[0] == 1 || pos[pos.size()-1] == n){
      sum = 2*n;
    }else{
      for(int i=0;i<pos.size();i++){
        if(i != 0 && pos.size() > 1){
          if(pos[i]-pos[i-1] > n - pos[i] + pos.size() - i - 1){
            if(2*pos[i] - pos[i-1] + pos.size() > sum){
              sum = 2*pos[i] - pos[i-1] + pos.size();
            }
            break;
          }
        }else{
          if(pos.size() == n - pos[0] && pos.size() > 1){
            sum = 2*n - pos[0];
          }else if(2*pos[i] >= 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum += 2*pos[i] - n - 1;
            if(pos.size() == 1){
              break;
            }
          }else if(2*pos[i] < 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum = 2*n - 2*(pos[0]-1);
            if(pos.size() == 1){
              break;
            }
          }
        }
      }
    }
  }
  cout << sum << "\n";
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  vector<int> vect;
  int n;
  string str;
  cin >> n;
  cin >> str;
  for(int i=0;i<str.size();i++){
    if(str[i] == '1'){
      vect.push_back(i);
    }
  }
  if(vect.size() == 0){
    cout << n << "\n";
  }else{
    cout << max(n-vect[0],vect[vect.size()-1]+1)*2 << "\n";
  }
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  vector<int> vect;
  int n;
  string str;
  cin >> n;
  cin >> str;
  for(int i=0;i<str.size();i++){
    if(str[i] == '1'){
      vect.push_back(i);
    }
  }
  if(vect.size() == 0){
    cout << n << "\n";
  }else{
    cout << max(n-vect[0],vect[0]+1)*2 << "\n";
  }
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  int n;
  vector<int> vect;
  vector<int> pos;
  string str;
  cin >> n;
  int sum = n;
  cin >> str;
  for(int i=0;i<n;i++){
    if(str[i] == '1'){
      vect.push_back(1);
      pos.push_back(i+1);
    }else{
      vect.push_back(0);
    }
  }
  if(pos.size() > 0){
    sum += pos.size();
    if(pos[0] == 1 || pos[pos.size()-1] == n){
      sum = 2*n;
    }else{
      for(int i=0;i<pos.size();i++){
        if(i != 0 && pos.size() > 1){
          if(pos[i]-pos[i-1] > n - pos[i] + pos.size() - i - 1){
            sum += 2*pos[i] - pos[i-1] - n;
            break;
          }
        }else{
          if(pos.size() == n - pos[0] && pos.size() > 1){
            sum = n - pos[0];
          }else if(2*pos[i] >= 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum += 2*pos[i] - n - 1;
            break;
          }else if(2*pos[i] < 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum = 2*n - 2*(pos[0]-1);
          }
        }
      }
    }
  }
  cout << sum << "\n";
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  int n;
  vector<int> vect;
  vector<int> pos;
  string str;
  cin >> n;
  int sum = n;
  cin >> str;
  for(int i=0;i<n;i++){
    if(str[i] == '1'){
      vect.push_back(1);
      pos.push_back(i+1);
    }else{
      vect.push_back(0);
    }
  }
  if(pos.size() > 0){
    sum += pos.size();
    if(pos[0] == 1 || pos[pos.size()-1] == 1){
      sum = 2*n;
    }else{
      for(int i=0;i<pos.size();i++){
        if(i != 0 && pos.size() > 1){
          if(pos[i]-pos[i-1] > n - pos[i] + pos.size() - i - 1){
            sum += 2*pos[i] - pos[i-1] - n;
            break;
          }
        }else{
          if(pos.size() == n - pos[0] && pos.size() > 1){
            sum = n - pos[0];
          }else if(2*pos[i] >= 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum += 2*pos[i] - n - 1;
            break;
          }else if(2*pos[i] < 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum = 2*n - 2*(pos[0]-1);
          }
        }
      }
    }
  }
  cout << sum << "\n";
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  int n;
  vector<int> pos;
  string str;
  cin >> n;
  int sum = n;
  cin >> str;
  for(int i=0;i<n;i++){
    if(str[i] == '1'){
      pos.push_back(i+1);
    }
  }
  if(pos.size() > 0){
    sum += pos.size();
    if(pos[0] == 1 || pos[pos.size()-1] == n){
      sum = 2*n;
    }else{
      for(int i=0;i<pos.size();i++){
        if(i != 0 && pos.size() > 1){
          if(pos[i]-pos[i-1] > n - pos[i] + pos.size() - i - 1){
            if(2*pos[i] - pos[i-1] + pos.size() > sum){
              sum = 2*pos[i] - pos[i-1] + pos.size();
            }
            break;
          }
        }else{
          if(pos.size() == n - pos[0] && pos.size() > 1){
            sum = n - pos[0];
          }else if(2*pos[i] >= 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum += 2*pos[i] - n - 1;
            if(pos.size() == 1){
              break;
            }
          }else if(2*pos[i] < 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum = 2*n - 2*(pos[0]-1);
            if(pos.size() == 1){
              break;
            }
          }
        }
      }
    }
  }
  cout << sum << "\n";
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  int n;
  vector<int> pos;
  string str;
  cin >> n;
  int sum = n;
  cin >> str;
  for(int i=0;i<n;i++){
    if(str[i] == '1'){
      pos.push_back(i+1);
    }
  }
  if(pos.size() > 0){
    sum += pos.size();
    if(pos[0] == 1 || pos[pos.size()-1] == n){
      sum = 2*n;
    }else{
      for(int i=0;i<pos.size();i++){
        if(i != 0 && pos.size() > 1){
          if(pos[i]-pos[i-1] > n - pos[i] + pos.size() - i - 1){
            sum += 2*pos[i] - pos[i-1] - n;
            break;
          }
        }else{
          if(pos.size() == n - pos[0] && pos.size() > 1){
            sum = n - pos[0];
            break;
          }else if(2*pos[i] >= 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum += 2*pos[i] - n - 1;
            break;
          }else if(2*pos[i] < 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum = 2*n - 2*(pos[0]-1);
            break;
          }
        }
      }
    }
  }
  cout << sum << "\n";
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  int n;
  vector<int> vect;
  vector<int> pos;
  string str;
  cin >> n;
  int sum = n;
  cin >> str;
  for(int i=0;i<n;i++){
    if(str[i] == '1'){
      vect.push_back(1);
      pos.push_back(i+1);
    }else{
      vect.push_back(0);
    }
  }
  if(pos.size() > 0){
    sum += pos.size();
    if(pos[0] == 1 || pos[pos.size()-1] == 1){
      sum = 2*n;
    }else{
      for(int i=0;i<pos.size();i++){
        if(i != 0 && pos.size() > 1){
          if(pos[i]-pos[i-1] > n - pos[i] + pos.size() - i - 1){
            sum += 2*pos[i] - pos[i-1] - n;
            break;
          }
        }else{
          if(pos.size() == n - pos[0]){
            sum = n - (pos[0] + 1);
          }else if(2*pos[i] >= 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum += 2*pos[i] - n - 1;
            break;
          }else if(2*pos[i] < 2*n - 2*(pos[0]-1) && pos.size() > 0){
            sum = 2*n - 2*(pos[0]-1);
          }
        }
      }
    }
  }
  cout << sum << "\n";
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


#include <bits/stdc++.h>
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

void test(){
  int n;
  vector<int> vect;
  vector<int> pos;
  string str;
  cin >> n;
  int sum = n;
  cin >> str;
  for(int i=0;i<n;i++){
    if(str[i] == '1'){
      vect.push_back(1);
      pos.push_back(i+1);
    }else{
      vect.push_back(0);
    }
  }
  if(pos.size() > 0){
    sum += pos.size();
    if(pos[0] == 1 || pos[pos.size()-1] == 1){
      sum = 2*n;
    }else{
      for(int i=0;i<pos.size();i++){
        if(i != 0 && pos.size() > 1){
          if(pos[i]-pos[i-1] > n - pos[i] + pos.size() - i - 1){
            sum += 2*pos[i] - pos[i-1] - n;
            break;
          }
        }else{
          if(pos[i] > n - pos[i] + pos.size() - i - 1 && pos.size() > 0){
            sum += 2*pos[i] - n - 1;
            break;
          }
        }
      }
    }
  }
  cout << sum << "\n";
}

int main() {
  int t;
  cin >> t;
  for(int i=0;i<t;i++){
    test();
  }
  return 0;
}


// https://codeforces.com/problemset/problem/1244/B

#include <iostream>
#include <vector>

std::vector<bool> reverse(std::vector<bool> v){
  std::vector<bool> o;
  for(auto it = v.rbegin(); it != v.rend(); ++it) o.push_back(*it);
  return o;
}

inline int max(int a, int b){
  return (a > b ? a : b);
}

int solve(std::vector<bool>::iterator b, std::vector<bool>::iterator e){

  int n = e - b;

  if(n == 0) return 0;
  if(n == 1){
    if(*b) return 2;
    else return 1;
  }

  int cnt = 0, cnt2 = 0;
  auto it = b;
  for(;it != e && !(*it); it++) ++cnt;

  if(it == e) --it; else ++cnt;
  if(*it) cnt2 = solve(it+1, e) + 1;

  return (cnt) + (cnt2 ? (max(cnt, cnt2)) : 0);
}

int solve(int n, std::vector<bool> v){

  if(n == 1 && !v[0]) return 1;

  int curPos = 0, minPos = n, maxPos = 0;
  int ans0, ans1, ans2;

  std::vector<bool> rv;
  rv = reverse(v);

  for(bool b : v){
    if(b) {
      maxPos = curPos;
      if(minPos == n) minPos = curPos;
    }
    ++curPos;
  }

  ans0 = 2 * max(n - minPos, maxPos + 1);
  if(ans0 == 2*n) return ans0;

  ans1 = solve(v.begin(), v.end());
  ans2 = solve(rv.begin(), rv.end());

  return max(ans0, max(ans1, ans2));
}

int main(){

  int t, n;
  char c;
  std::vector<bool> s;

  std::cin >> t;
  for(int i = 0; i < t; ++i){
    std::cin >> n;
    for(int j = 0; j < n; ++j){
      std::cin >> c;
      s.push_back(c - '0');
    }

    std::cout << solve(n, s) << std::endl;

    s.erase(s.begin(), s.end());
  }

  return 0;
}


// https://codeforces.com/problemset/problem/1244/B

#include <iostream>
#include <vector>

std::vector<bool> reverse(std::vector<bool> v){
  std::vector<bool> o;
  for(auto it = v.rbegin(); it != v.rend(); ++it) o.push_back(*it);
  return o;
}

inline int max(int a, int b){
  return (a > b ? a : b);
}

int solve(std::vector<bool>::iterator b, std::vector<bool>::iterator e){

  int n = e - b;

  if(n == 0) return 0;
  if(n == 1){
    if(*b) return 2;
    else return 1;
  }

  int cnt = 0, cnt2 = 0;
  auto it = b;
  for(;it != e && !(*it); it++) ++cnt;

  if(it == e) --it; else ++cnt;
  if(*it) cnt2 = solve(it+1, e) + 1;

  return (cnt) + (cnt2 ? (max(cnt, cnt2)) : 0);
}

int solve(int n, std::vector<bool> v){

  if(n == 1) return 1;

  int curPos = 0, minPos = n, maxPos = 0;
  int ans0, ans1, ans2;

  std::vector<bool> rv;
  rv = reverse(v);

  for(bool b : v){
    if(b) {
      maxPos = curPos;
      if(minPos == n) minPos = curPos;
    }
    ++curPos;
  }

  ans0 = 2 * max(n - minPos, maxPos + 1);
  if(ans0 == 2*n) return ans0;

  ans1 = solve(v.begin(), v.end());
  ans2 = solve(rv.begin(), rv.end());

  return max(ans0, max(ans1, ans2));
}

int main(){

  int t, n;
  char c;
  std::vector<bool> s;

  std::cin >> t;
  for(int i = 0; i < t; ++i){
    std::cin >> n;
    for(int j = 0; j < n; ++j){
      std::cin >> c;
      s.push_back(c - '0');
    }

    std::cout << solve(n, s) << std::endl;

    s.erase(s.begin(), s.end());
  }

  return 0;
}


// https://codeforces.com/problemset/problem/1244/B

#include <iostream>
#include <vector>

/*
 * void printVector(std::vector<bool> b){
 *   for(bool c : b)
 *     std::cout << c;
 *   std::cout << std::endl;
 * }
 */

std::vector<bool> reverse(std::vector<bool> v){
  std::vector<bool> o;
  for(auto it = v.rbegin(); it != v.rend(); ++it) o.push_back(*it);
  return o;
}

inline int max(int a, int b){
  return (a > b ? a : b);
}

int solve(std::vector<bool>::iterator b, std::vector<bool>::iterator e){

  int n = e - b;

  if(n == 0) return 0;
  if(n == 1){
    if(*b) return 2;
    else return 1;
  }

  int cnt = 0, cnt2 = 0, cnt3 = 0;
  auto it = b;
  for(;it != e; it++){
    ++cnt;
    if(*it) break;
  }

  if(it == e) --it;

  if(*it){
    cnt2 = solve(it+1, e) + 1;

    std::vector<bool> v;
    for(auto it2 = b; it2 != e; ++it2){
      if(it2 == it) v.push_back(0);
      else v.push_back(*it2);
    }
    cnt3 = solve(v.begin(), v.end());
  }

  return max((cnt) + (cnt2 ? (max(cnt, cnt2)) : 0), cnt3);
}

int main(){

  int t, n;
  int s1, s2;
  char c;
  std::vector<bool> s;
  std::vector<bool> r;

  std::cin >> t;
  for(int i = 0; i < t; ++i){
    std::cin >> n;
    for(int j = 0; j < n; ++j){
      std::cin >> c;
      s.push_back(c - '0');
    }
    r = reverse(s);

    s1 = solve(s.begin(), s.end());
    s2 = solve(r.begin(), r.end());

    std::cout << max(s1, s2) << std::endl;

    s.erase(s.begin(), s.end());
    r.erase(r.begin(), r.end());
  }

  return 0;
}


// https://codeforces.com/problemset/problem/1244/B

#include <iostream>
#include <vector>

std::vector<bool> reverse(std::vector<bool> v){
  std::vector<bool> o;
  for(auto it = v.rbegin(); it != v.rend(); ++it) o.push_back(*it);
  return o;
}

inline int max(int a, int b){
  return (a > b ? a : b);
}

int solve(std::vector<bool>::iterator b, std::vector<bool>::iterator e){

  int n = e - b;

  if(n == 0) return 0;
  if(n == 1){
    if(*b) return 2;
    else return 1;
  }

  int cnt = 0, cnt2 = 0;
  auto it = b;
  for(;it != e && !(*it); it++) ++cnt;

  if(it == e) --it; else ++cnt;
  if(*it) cnt2 = solve(it+1, e) + 1;

  return (cnt) + (cnt2 ? (max(cnt, cnt2)) : 0);
}

int solve(int n, std::vector<bool> v){

  int curPos = 0, minPos = n, maxPos = 0;
  int ans0, ans1, ans2;

  std::vector<bool> rv;
  rv = reverse(v);

  for(bool b : v){
    if(b) {
      maxPos = curPos;
      if(minPos == n) minPos = curPos;
    }
    ++curPos;
  }

  ans0 = 2 * max(n - minPos, maxPos + 1);
  if(ans0 == 2*n) return ans0;

  ans1 = solve(v.begin(), v.end());
  ans2 = solve(rv.begin(), rv.end());

  return max(ans0, max(ans1, ans2));
}

int main(){

  int t, n;
  char c;
  std::vector<bool> s;

  std::cin >> t;
  for(int i = 0; i < t; ++i){
    std::cin >> n;
    for(int j = 0; j < n; ++j){
      std::cin >> c;
      s.push_back(c - '0');
    }

    std::cout << solve(n, s) << std::endl;

    s.erase(s.begin(), s.end());
  }

  return 0;
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
    int q;
    cin>>q;
    for(int qq=0;qq<q;qq++){
        int n;
        cin>>n;
        int res1=-1,res2=-1;
        for(int i=0;i<n;i++){
            char x;
            cin>>x;
            if(res1==-1 && x=='1') res1=i;
            if(x=='1') res2=i+1;
        }
        if(res1==-1) cout<<n<<endl;
        else if(res1<=n/2+n%2) cout<<max(res2*2,(n-res1)*2)<<endl;
        else cout<<max(res1*2,(n-res2)*2)<<endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
    int q;
    cin>>q;
    for(int qq=0;qq<q;qq++){
        int n;
        cin>>n;
        int res=-1;
        for(int i=0;i<n;i++){
            char x;
            cin>>x;
            if(res==-1 && x=='1') res=i;
        }
        if(res==-1) cout<<n<<endl;
        else if(res<n/2+n%2) cout<<(n-res)*2<<endl;
        else cout<<res*2<<endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
    int q;
    cin>>q;
    for(int qq=0;qq<q;qq++){
        int n;
        cin>>n;
        int res1=-1,res2=-1;
        for(int i=0;i<n;i++){
            char x;
            cin>>x;
            if(res1==-1 && x=='1') res1=i;
            if(x=='1') res2=i+1;
        }
        //cout<<res1<<' '<<res2<<endl;
        if(res1==-1) cout<<n<<endl;
        else{
            int res=max(res2*2,max((n-res1)*2,max(res,max(res1*2,(n-res2)*2))));
            //max(res,max(res1*2,(n-res2)*2));
            cout<<res<<endl;
        }
    }
}


#include <bits/stdc++.h>
using namespace std;
#define ll long long
int main(){
    int q;
    cin>>q;
    for(int qq=0;qq<q;qq++){
        int n;
        cin>>n;
        int res1=-1,res2=-1;
        for(int i=0;i<n;i++){
            char x;
            cin>>x;
            if(res1==-1 && x=='1') res1=i;
            if(x=='1') res2=i+1;
        }
        //cout<<res1<<' '<<res2<<endl;
        if(res1==-1) cout<<n<<endl;
        else{
            int res=max(res2*2,(n-res1)*2);
            res=max(res,max(res1*2,(n-res2)*2));
            cout<<res<<endl;
        }
    }
}


#include <bits/stdc++.h>

#define ld long double
#define ll long long
#define ull unsigned long long
#define F first
#define S second
#define nl cout << endl
#define pii pair <ll, ll>
#define pb push_back
#define mp make_pair
#define pi 3.14159265358979323846264
#define y1 abacaba
#define fn "abc"
#define sz(a) (int)(a).size()
#define all(a) (a).begin(), (a).end()
#define Need_For_Speed ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define __lcm(a, b) (a * b) / __gcd(a, b)

using namespace std;

const long long MXN = 1e6 + 1;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;

ll q;

int main () {

    cin >> q;
    while(q--) {
        ll n;
        string s;
        cin >> n >> s;
        ll pos = -1;
        for (int i = 0; i < sz(s); i++) {
            if (s[i] == '1') {
                pos = i;
                break;
            }
        }
        if (pos == -1) {
            cout << n;
        } else {
            ll pos1 = 0;
            for (int i = sz(s) - 1; i >= 0; i--) {
                if (s[i] == '1') {
                    pos1 = i;
                    break;
                }
            }
            ll mn = min(pos, n - pos1);
            cout << (n - mn) * 2;
        }
        nl;
    }
    return 0;
}


#include <bits/stdc++.h>

#define ld long double
#define ll long long
#define ull unsigned long long
#define F first
#define S second
#define nl cout << endl
#define pii pair <ll, ll>
#define pb push_back
#define mp make_pair
#define pi 3.14159265358979323846264
#define y1 abacaba
#define fn "abc"
#define sz(a) (int)(a).size()
#define all(a) (a).begin(), (a).end()
#define Need_For_Speed ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define __lcm(a, b) (a * b) / __gcd(a, b)

using namespace std;

const long long MXN = 1e6 + 1;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;

ll q;

int main () {

    cin >> q;
    while(q--) {
        ll n;
        string s;
        cin >> n >> s;
        ll cnt = 0;
        for (int i = 0; i < sz(s); i++) {
            if (s[i] == '1') {
                cnt ++;
            }
        }
        if (s[0] == '1' || s[sz(s) - 1] == '1') {
            cout << n * 2;
            nl;
        }else if (!cnt) {
            cout << n;
            nl;
        } else {
            ll ans1 = 0, ans2 = 0;
            ll t = cnt;
            for (int i = 0; i < sz(s); i++) {
                if (s[i] == '1') {
                    if (t == 1) {
                        ans1 = (i + 1) * 2;
                        break;
                    } else {
                        t --;
                    }
                }
            }
            for (int i = sz(s) - 1; i >= 0; i--) {
                if (s[i] == '1') {
                    if (cnt == 1) {
                        ans2 = (i + 1) * 2;
                        break;
                    } else {
                        cnt --;
                    }
                }
            }
            cout << max(ans1, ans2);
            nl;
        }
    }
    return 0;
}


#include <bits/stdc++.h>

#define ld long double
#define ll long long
#define ull unsigned long long
#define F first
#define S second
#define nl cout << endl
#define pii pair <ll, ll>
#define pb push_back
#define mp make_pair
#define pi 3.14159265358979323846264
#define y1 abacaba
#define fn "abc"
#define sz(a) (int)(a).size()
#define all(a) (a).begin(), (a).end()
#define Need_For_Speed ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define __lcm(a, b) (a * b) / __gcd(a, b)

using namespace std;

const long long MXN = 1e6 + 1;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;

ll q;

int main () {

    cin >> q;
    while(q--) {
        ll n;
        string s;
        cin >> n >> s;
        ll pos = -1;
        for (int i = 0; i < sz(s); i++) {
            if (s[i] == '1') {
                pos = i;
                break;
            }
        }
        if (pos == -1) {
            cout << n;
        } else {
            ll pos1 = 0;
            for (int i = sz(s) - 1; i >= 0; i--) {
                if (s[i] == '1') {
                    pos1 = i;
                    break;
                }
            }
            if (pos1 == n - 1 || pos == 0) {
                cout << n * 2;
            } else {
                ll mn = min(pos, n - pos1);
                cout << (n - mn) * 2;
            }
        }
        nl;
    }
    return 0;
}