/*===================================================================================================================

                                                   // BY - ABHISHEK MALIK  //

=====================================================================================================================*/
#include<bits/stdc++.h>
#define ull unsigned long long
#define ll long long int
#define pb push_back
#define f first
#define s second
#define len length
#define mk make_pair
#define inf  1e9
#define mini -1
#define MOD 1000000007
#define all(v) (v).begin(),(v).end()
#define mset(v,x) memset(v,x,sizeof(v))
#define MODSET(d) if ((d) >= MOD) d %= MOD;
#define inp(x) (scanf("%d",&x))
#define inp2(x,y) (scanf("%d%d",&x,&y))
#define inp3(x,y,z) (scanf("%d%d%d",&x,&y,&z))
#define inp4(x,y,z,w) (scanf("%d%d%d%d",&x,&y,&z,&w))
#define inpl(d) scanf("%lld",&d)
#define inpl2(a,b) scanf("%lld%lld",&a,&b)
#define inpl3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c)
#define inpl4(a,b,c,d) scanf("%lld%lld%lld%lld",&a,&b,&c,&d)
using namespace std;
//vector<int >v[100005];
//set<string >stA,stB,stC,stD;
//stack<int >st;
//priority_queue< pair <int ,int > >pq;
//vector<ll >a,b,c,d;
set<ll >st[5];
//char arr[51][51];
ll price[200005],bcolor[200005],fcolor[200005],buyer[200005];
//ll dp[1005][3];
//bool vis[1000005];
//map<string ,int >mp,mp2;
//map<string ,int >::iterator it,it2;
set<ll >::iterator it,its2;
//vector< pair <int ,pair<int ,int > > >vpp;
//vector<pair <ll,ll > >vp;
//vector< pair < int,int > >v[200005],adj2[100005];
/********************************************* YOUR CODE GOES FROM HERE ************************************************/
int main()
{
   ll n,m;
   inpl(n);
   for(ll i=1;i<=n;i++)
     inpl(price[i]);

   for(ll i=1;i<=n;i++)
     inpl(fcolor[i]);

   for(ll i=1;i<=n;i++)
    inpl(bcolor[i]);

    inpl(m);
   for(ll i=1;i<=m;i++)
     inpl(buyer[i]);

   for(ll i=1;i<=n;i++)
   {
       st[fcolor[i]].insert(price[i]);
       st[bcolor[i]].insert(price[i]);
   }
   for(ll i=1;i<=m;i++)
   {
       if(st[buyer[i]].size()==0)
       {
           cout<<"-1 ";
       }
       else
       {
           it=st[buyer[i]].begin();
           cout<<*it<<" ";
            for(int j=1;j<=3;j++)
            st[j].erase(*it);
       }
   }
}


/*===================================================================================================================

                                                   // BY - ABHISHEK MALIK  //

=====================================================================================================================*/
#include<bits/stdc++.h>
#define ull unsigned long long
#define ll long long int
#define pb push_back
#define f first
#define s second
#define len length
#define mk make_pair
#define inf  1e9
#define mini -1
#define MOD 1000000007
#define all(v) (v).begin(),(v).end()
#define mset(v,x) memset(v,x,sizeof(v))
#define MODSET(d) if ((d) >= MOD) d %= MOD;
#define inp(x) (scanf("%d",&x))
#define inp2(x,y) (scanf("%d%d",&x,&y))
#define inp3(x,y,z) (scanf("%d%d%d",&x,&y,&z))
#define inp4(x,y,z,w) (scanf("%d%d%d%d",&x,&y,&z,&w))
#define inpl(d) scanf("%lld",&d)
#define inpl2(a,b) scanf("%lld%lld",&a,&b)
#define inpl3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c)
#define inpl4(a,b,c,d) scanf("%lld%lld%lld%lld",&a,&b,&c,&d)
using namespace std;
//vector<int >v[100005];
//set<string >stA,stB,stC,stD;
//stack<int >st;
//priority_queue< pair <int ,int > >pq;
//vector<ll >a,b,c,d;
set<ll >st[5];
//char arr[51][51];
ll price[200005],bcolor[200005],fcolor[200005];
//ll dp[1005][3];
//bool vis[1000005];
//map<string ,int >mp,mp2;
//map<string ,int >::iterator it,it2;
set<ll >::iterator it,its2;
//vector< pair <int ,pair<int ,int > > >vpp;
//vector<pair <ll,ll > >vp;
//vector< pair < int,int > >v[200005],adj2[100005];
/********************************************* YOUR CODE GOES FROM HERE ************************************************/
int main()
{
   ll n,m,k,t;
   inpl(n);
   for(ll i=1;i<=n;i++)
     inpl(price[i]);

   for(ll i=1;i<=n;i++)
     inpl(fcolor[i]);

   for(ll i=1;i<=n;i++)
    inpl(bcolor[i]);

   for(ll i=1;i<=n;i++)
   {
       st[fcolor[i]].insert(price[i]);
       st[bcolor[i]].insert(price[i]);
   }
   inpl(m);
   for(ll i=1;i<=m;i++)
   {
       inpl(k);
       if(st[k].size()==0)
       {
           cout<<"-1 ";
       }
       else
       {
           t=*st[k].begin();
           cout<<t<<" ";
            for(int j=1;j<=3;j++)
            st[j].erase(t);
       }
   }
}


/*===================================================================================================================

                                                   // BY - ABHISHEK MALIK  //

=====================================================================================================================*/
#include<bits/stdc++.h>
#define ull unsigned long long
#define ll long long int
#define pb push_back
#define f first
#define s second
#define len length
#define mk make_pair
#define inf  1e9
#define mini -1
#define MOD 1000000007
#define all(v) (v).begin(),(v).end()
#define mset(v,x) memset(v,x,sizeof(v))
#define MODSET(d) if ((d) >= MOD) d %= MOD;
#define inp(x) (scanf("%d",&x))
#define inp2(x,y) (scanf("%d%d",&x,&y))
#define inp3(x,y,z) (scanf("%d%d%d",&x,&y,&z))
#define inp4(x,y,z,w) (scanf("%d%d%d%d",&x,&y,&z,&w))
#define inpl(d) scanf("%lld",&d)
#define inpl2(a,b) scanf("%lld%lld",&a,&b)
#define inpl3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c)
#define inpl4(a,b,c,d) scanf("%lld%lld%lld%lld",&a,&b,&c,&d)
using namespace std;
//vector<int >v[100005];
//set<string >stA,stB,stC,stD;
//stack<int >st;
//priority_queue< pair <int ,int > >pq;
//vector<ll >a,b,c,d;
set<ll >st[1000005];
//char arr[51][51];
ll price[1000005],bcolor[1000005],fcolor[1000005],buyer[1000005];
//ll dp[1005][3];
//bool vis[1000005];
//map<string ,int >mp,mp2;
//map<string ,int >::iterator it,it2;
set<ll >::iterator it,its2;
//vector< pair <int ,pair<int ,int > > >vpp;
//vector<pair <ll,ll > >vp;
//vector< pair < int,int > >v[200005],adj2[100005];
/********************************************* YOUR CODE GOES FROM HERE ************************************************/
int main()
{
   ll n,m;
   inpl(n);
   for(ll i=1;i<=n;i++)
     inpl(price[i]);

   for(ll i=1;i<=n;i++)
     inpl(fcolor[i]);

   for(ll i=1;i<=n;i++)
    inpl(bcolor[i]);

    inpl(m);
   for(ll i=1;i<=m;i++)
     inpl(buyer[i]);

   for(ll i=1;i<=n;i++)
   {
       st[fcolor[i]].insert(price[i]);
       st[bcolor[i]].insert(price[i]);
   }
   for(ll i=1;i<=m;i++)
   {
       if(st[buyer[i]].size()==0)
       {
           cout<<"-1 ";
       }
       else
       {
           it=st[buyer[i]].begin();
           cout<<*it<<" ";
           if(st[1].find(*it)!=st[1].end())
            st[1].erase(*it);
           if(st[2].find(*it)!=st[2].end())
            st[2].erase(*it);
           if(st[3].find(*it)!=st[3].end())
            st[3].erase(*it);
       }
   }
}


/*===================================================================================================================

                                                   // BY - ABHISHEK MALIK  //

=====================================================================================================================*/
#include<bits/stdc++.h>
#define ull unsigned long long
#define ll long long int
#define pb push_back
#define f first
#define s second
#define len length
#define mk make_pair
#define inf  1e9
#define mini -1
#define MOD 1000000007
#define all(v) (v).begin(),(v).end()
#define mset(v,x) memset(v,x,sizeof(v))
#define MODSET(d) if ((d) >= MOD) d %= MOD;
#define inp(x) (scanf("%d",&x))
#define inp2(x,y) (scanf("%d%d",&x,&y))
#define inp3(x,y,z) (scanf("%d%d%d",&x,&y,&z))
#define inp4(x,y,z,w) (scanf("%d%d%d%d",&x,&y,&z,&w))
#define inpl(d) scanf("%lld",&d)
#define inpl2(a,b) scanf("%lld%lld",&a,&b)
#define inpl3(a,b,c) scanf("%lld%lld%lld",&a,&b,&c)
#define inpl4(a,b,c,d) scanf("%lld%lld%lld%lld",&a,&b,&c,&d)
using namespace std;
//vector<int >v[100005];
//set<string >stA,stB,stC,stD;
//stack<int >st;
//priority_queue< pair <int ,int > >pq;
//vector<ll >a,b,c,d;
set<ll >st[5];
//char arr[51][51];
ll price[200005],bcolor[200005],fcolor[200005],buyer[200005];
//ll dp[1005][3];
//bool vis[1000005];
//map<string ,int >mp,mp2;
//map<string ,int >::iterator it,it2;
set<ll >::iterator it,its2;
//vector< pair <int ,pair<int ,int > > >vpp;
//vector<pair <ll,ll > >vp;
//vector< pair < int,int > >v[200005],adj2[100005];
/********************************************* YOUR CODE GOES FROM HERE ************************************************/
int main()
{
   ll n,m;
   inpl(n);
   for(ll i=1;i<=n;i++)
     inpl(price[i]);

   for(ll i=1;i<=n;i++)
     inpl(fcolor[i]);

   for(ll i=1;i<=n;i++)
    inpl(bcolor[i]);

    inpl(m);
   for(ll i=1;i<=m;i++)
     inpl(buyer[i]);

   for(ll i=1;i<=n;i++)
   {
       st[fcolor[i]].insert(price[i]);
       st[bcolor[i]].insert(price[i]);
   }
   for(ll i=1;i<=m;i++)
   {
       if(st[buyer[i]].size()==0)
       {
           cout<<"-1 ";
       }
       else
       {
           it=st[buyer[i]].begin();
           cout<<*it<<" ";
           if(st[1].find(*it)!=st[1].end())
            st[1].erase(*it);
           if(st[2].find(*it)!=st[2].end())
            st[2].erase(*it);
           if(st[3].find(*it)!=st[3].end())
            st[3].erase(*it);
       }
   }
}


#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>
#include<queue>
//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;

};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i,tem;
    cin>>n;
    rl temp;
    map <int,int> taken;

    vector<rl> a;
    queue <int> q[4];
    For(i,0,n)
    {
        cin>>temp.price;
        a.pb(temp);
    }
    For(i,0,n)
    {
        cin>>a.at(i).f;
    }
    For(i,0,n)
    {
        cin>>a.at(i).b;
    }
    sort(all(a));
    for(auto itv=a.begin();itv!=a.end();itv++)
    {
        q[(*itv).f].push((*itv).price);
        q[(*itv).b].push((*itv).price);

    }
    int m;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        if (q[tem].empty())
            cout<<-1;
        else
        {
            while(taken[q[tem].front()]!=0)
            {
                q[tem].pop();
            }
            if(q[tem].empty())
                cout<<-1;
            else if (taken[q[tem].front()]==0)
            {

                taken[q[tem].front()]=1;
                cout<<q[tem].front()<<" ";
                q[tem].pop();
            }
        }

    }

    //cout<<1;
    return 0;

}


#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>

//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;
};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i;
    cin>>n;
    rl temp;
    vector<rl> a;
    For(i,0,n)
    {
        cin>>temp.price;
        a.pb(temp);
    }
    For(i,0,n){
        cin>>a.at(i).f;
    }
    For(i,0,n){
        cin>>a.at(i).b;
    }
    set <rl> aa(all(a));
    auto it=aa.begin();
    int m,tem;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        int flag=1;
        for(it=aa.begin();flag&&it!=aa.end();it++)
        {
            if((*it).f==tem || (*it).b==tem)
            {
                flag=0;
                cout<<(*it).price<<" ";
                aa.erase(it);
            }
        }

        if(flag)
            cout<<-1<<" ";
    }
    //cout<<1;
    return 0;

}


#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>
#include<queue>
//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;

};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i,tem;
    cin>>n;
    rl temp;
    map <int,int> taken;

    vector<rl> a;
    queue <int> q[4];
    For(i,0,n)
    {
        cin>>temp.price;
        a.pb(temp);
    }
    For(i,0,n)
    {
        cin>>a.at(i).f;
    }
    For(i,0,n)
    {
        cin>>a.at(i).b;
    }
    sort(all(a));
    for(auto itv=a.begin();itv!=a.end();itv++)
    {
        q[(*itv).f].push((*itv).price);
        q[(*itv).b].push((*itv).price);

    }
    int m;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        if (q[tem].empty())
            cout<<-1<<" ";
        else
        {
            while(taken[q[tem].front()]!=0)
            {
                q[tem].pop();
            }
            if(q[tem].empty())
                cout<<-1<<" ";
            else if (taken[q[tem].front()]==0)
            {

                taken[q[tem].front()]=1;
                cout<<q[tem].front()<<" ";
                q[tem].pop();
            }
        }

    }

    //cout<<1;
    return 0;

}


#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>

//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;
int* taken;
};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i,tem;
    cin>>n;
    rl temp;
    int tak[n];
    memset(tak,0,n*int(sizeof(tak[0])));
    set <rl> aa[3];
    vector<rl> a;

    For(i,0,n)
    {
        cin>>temp.price;
        temp.taken = tak+i;
        a.pb(temp);
    }
    For(i,0,n)
    {
        cin>>a.at(i).f;
    }
    For(i,0,n)
    {
        cin>>a.at(i).b;
    }
    for(auto itv=a.begin();itv!=a.end();itv++)
    {
        aa[(*itv).f-1].insert(*itv);
        aa[(*itv).b-1].insert(*itv);

    }
    int m;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        int flag=1;
        for(auto it=aa[tem-1].begin();flag&&it!=aa[tem-1].end();it++)
        {
            if((*it).f==tem || (*it).b==tem)
            {
                if (*((*it).taken))
                    aa[tem-1].erase(it);
                else
                {
                    flag=0;
                    (*((*it).taken))=1;
                    cout<<(*it).price<<" ";
                    aa[tem-1].erase(it);
                }
            }
        }

        if(flag)
            cout<<-1<<" ";
    }
    //cout<<1;
    return 0;

}


#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>

//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;
int* taken;
};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i,tem;
    cin>>n;
    rl temp;
    int tak[n];
    memset(tak,0,n*int(sizeof(tak[0])));
    set <rl> aa[3];
    vector<rl> a;

    For(i,0,n)
    {
        cin>>temp.price;
        temp.taken = tak+i;
        a.pb(temp);
    }
    For(i,0,n)
    {
        cin>>a.at(i).f;
    }
    For(i,0,n)
    {
        cin>>a.at(i).b;
    }
    for(auto itv=a.begin();itv!=a.end();itv++)
    {
        aa[(*itv).f-1].insert(*itv);
        aa[(*itv).b-1].insert(*itv);

    }
    int m;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        int flag=1;
        for(auto it=aa[tem-1].begin();flag&&it!=aa[tem-1].end();it++)
        {
            if((*it).f==tem || (*it).b==tem)
            {
                if ((*((*it).taken)))
                    aa[tem-1].erase(it);
                else
                {
                    flag=0;
                    (*((*it).taken))=1;
                    cout<<(*it).price<<" ";
                    aa[tem-1].erase(it);
                }
            }
        }

        if(flag)
            cout<<-1<<" ";
    }

    //cout<<1;
    return 0;

}


#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>

//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;
};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i;
    cin>>n;
    rl temp;
    vector<rl> a;
    For(i,0,n)
    {
        cin>>temp.price;
        a.pb(temp);
    }
    For(i,0,n){
        cin>>a.at(i).f;
    }
    For(i,0,n){
        cin>>a.at(i).b;
    }
    set <rl> aa(all(a));
    auto it=aa.begin();
    int m,tem;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        int flag=1;
        for(it=aa.begin();it!=aa.end();it++)
        {
            if((*it).f==tem || (*it).b==tem)
            {
                flag=0;
                cout<<(*it).price<<" ";
                aa.erase(it);
            }
        }

        if(flag)
            cout<<-1<<" ";
    }
    //cout<<1;
    return 0;

}


#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>

//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;
};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i;
    cin>>n;
    rl temp;
    temp.f=0;
    temp.b=0;

    set <rl> aa;
    auto it=aa.begin();
    For(i,0,n)
    {
        cin>>temp.price;
        aa.inser(temp);
    }
    for(it=aa.begin();it!=aa.end();it++){
        cin>>(*it).f;
    }
    for(it=aa.begin();it!=aa.end();it++){
        cin>>(*it).f;
    }

    int m,tem;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        int flag=1;
        for(it=aa.begin();flag&&it!=aa.end();it++)
        {
            if((*it).f==tem || (*it).b==tem)
            {
                flag=0;
                cout<<(*it).price<<" ";
                aa.erase(it);
            }
        }

        if(flag)
            cout<<-1<<" ";
    }
    //cout<<1;
    return 0;

}


#include <bits/stdc++.h>
#include <vector>
using namespace std;

int main(){
    long int n,m,a1=0,b1=0,fin;
    cin>>n;
    vector<long long int> p(n);
    vector<long long int> r;
    vector<long long int> a(n);
    vector<long long int> b(n);
    for(long int i=0;i<n;i++){
        cin>>p[i];
    }
    for(long int i=0;i<n;i++){
        cin>>a[i];
    }
    for(long int i=0;i<n;i++){
        cin>>b[i];
    }
    cin>>m;
    vector<int> c(m);
    for(long int i=0;i<m;i++){
        cin>>c[i];
    }

    for(long int j=0;j<m;j++){
        long int amin=1000000001;
        long int bmin=1000000001;
        long int minim=1000000001;
        for(long int k=0;k<p.size();k++){
            if(a[k]==c[j]){
                if(p[k]<amin){
                    amin=p[k];
                    a1=k;
                }
            }
            if(b[k]==c[j]){
                if(p[k]<bmin){
                    bmin=p[k];
                    b1=k;
                }
            }
        }
        if(amin<bmin){
            minim=amin;
            fin=a1;
        }
        else{
            fin=b1;
            minim=bmin;
        }
        if(minim==1000000001){
            r.push_back(-1);
        }
        else{
            r.push_back(minim);
        }
        if(p.size()>0 && r[j]!=-1){
            p.erase(p.begin()+fin);
            a.erase(a.begin()+fin);
            b.erase(b.begin()+fin);
        }

        cout<<r[j]<<" ";
    }
    return 0;
}


#include<iostream>
#include<set>
#include<vector>
#include<algorithm>
#include<cmath>
#include<string.h>

//#include<stdio.h>
//#define a.pb(c) push_back(c)
//#define pri(n) cout<<n<<"\n"
#define all(c) c.begin(),c.end()
#define allarr(c) c,c+sizeof(c)
//#define revall(c) c.rbegin(),c.rend()
#define pb push_back
typedef long long ll;
#define inf 1000000000
//typedef vector <int> vi;
//typedef pair<int,int> pii;
#define For(i,a,b) for(i=a;i<b;i++)
using namespace std;

struct rl{
ll price;
int f;
int b;
int* taken;
};
bool operator<(const rl& a, const rl& b)
{
    return a.price<b.price;
}

void pri(int x)
{
    cout<<x<<" ";

}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    int n,i,tem;
    cin>>n;
    rl temp;
    int tak[n];
    memset(tak,0,n*int(sizeof(tak[0])));
    set <rl> aa[3];
    vector<rl> a;

    For(i,0,n)
    {
        cin>>temp.price;
        temp.taken = tak+i;
        a.pb(temp);
    }
    For(i,0,n)
    {
        cin>>a.at(i).f;
    }
    For(i,0,n)
    {
        cin>>a.at(i).b;
    }
    for(auto itv=a.begin();itv!=a.end();itv++)
    {
        aa[(*itv).f-1].insert(*itv);
        aa[(*itv).b-1].insert(*itv);

    }
    int m;
    cin>>m;
    For(i,0,m){
        cin>>tem;
        int flag=1;
        for(auto it=(aa[tem-1].begin());flag && it!=(aa[tem-1].end());it++)
        {
            if((*it).f==tem || (*it).b==tem)
            {
                if ((*((*it).taken))==1)
                    {
                    //(aa[tem-1]).erase(it);
                    }
                else
                {
                    flag=0;
                    (*((*it).taken))=1;
                    cout<<(*it).price<<" ";
                    aa[tem-1].erase(it);
                }
            }
        }

        if(flag)
            cout<<-1<<" ";
    }

    //cout<<1;
    return 0;

}


// Created by Priyanshu

#include <bits/stdc++.h>
#define M                    1000000007
#define pi                   3.14159265358979323846
#define ll                   long long
#define lld                  long double

// Pair
#define pii                  pair<int, int>
#define pll                  pair<ll, ll>

// Vector
#define vl                   vector<ll >
#define vi                   vector<int>
#define vpi                  vector<pii>
#define vpl                  vector<pll>
#define pb                   push_back
#define mp                   make_pair

// Search
#define lb                   lower_bound
#define ub                   upper_bound
#define mina                 *min_element
#define mama                 *max_element
#define bsrch                binary_search

////////
#define F                    first
#define S                    second
#define cel(x,a)             ((x + a - 1) / a)
#define all(v)               v.begin(), v.end()
#define lcm(m, n)            ((m / __gcd(m, n))*n)
#define deb(x)               cout << #x<<" = "<<x<<'\n'
#define ms(arr, v)           memset(arr, v, sizeof(arr))
#define ps(x,y)              fixed << setprecision(y) << x
#define _X_                  ios_base::sync_with_stdio(false); cin.tie(NULL)

// Input / Output
#define scn(str)             scanf("%s", str)
#define pri(str)             printf("%s\n", str)
#define wws(k)               ww(k), putchar(' ')
#define inp(ar, n)           for (int ele = 0; ele < n; ele++)ar[ele] = read()
inline ll   read()           { ll sign = 1; ll x = 0; char ch; while (!isdigit(ch = getchar())) if (ch == '-') sign = -1; while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * sign;}
inline void wonl()           { putchar('\n');}
inline void ww(ll k)         { if (k < 0) putchar('-'), k *= -1; char ch[20]; int num = 0; while (k)ch[++num] = k % 10, k /= 10; if (num == 0) ch[++num] = 0; while (num)putchar(ch[num--] + '0');}

using namespace std;
const int N = 1e5 + 4;

template <typename T, typename... V>
inline void wonl(T t, V... v) {ww(t); if (sizeof...(v))putchar(' '); wonl(v...);}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    // _X_;
    // clock_t time_req = clock();

    long long int n = read(), p[n], a;
    inp(p, n);

    map<long long int, pii> pm;
    multiset<long long int> o[4];

    for (long long int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].F = a;
    }
    for (long long int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].S = a;
    }

    long long int m = read();
    while (m--) {
        a = read();
        if (o[a].size() == 0) {
            wws(-1);
            continue;
        }

        auto it = o[a].begin();

        wws(*it);

        long long int x = pm[*it].F, y = pm[*it].S;
        auto it1 = o[x].find(*it);
        auto it2 = o[y].find(*it);

        o[x].erase(it1), o[y].erase(it2);

    }

    // time_req = clock() - time_req;
    // cout << (float)time_req / CLOCKS_PER_SEC;
    return 0;
}


// Created by Priyanshu

#include <bits/stdc++.h>
#define M                    1000000007
#define pi                   3.14159265358979323846
#define ll                   long long
#define lld                  long double

// Pair
#define pii                  pair<int, int>
#define pll                  pair<ll, ll>

// Vector
#define vl                   vector<ll >
#define vi                   vector<int>
#define vpi                  vector<pii>
#define vpl                  vector<pll>
#define pb                   push_back
#define mp                   make_pair

// Search
#define lb                   lower_bound
#define ub                   upper_bound
#define mina                 *min_element
#define mama                 *max_element
#define bsrch                binary_search

////////
#define F                    first
#define S                    second
#define cel(x,a)             ((x + a - 1) / a)
#define all(v)               v.begin(), v.end()
#define lcm(m, n)            ((m / __gcd(m, n))*n)
#define deb(x)               cout << #x<<" = "<<x<<'\n'
#define ms(arr, v)           memset(arr, v, sizeof(arr))
#define ps(x,y)              fixed << setprecision(y) << x
#define _X_                  ios_base::sync_with_stdio(false); cin.tie(NULL)

// Input / Output
#define scn(str)             scanf("%s", str)
#define pri(str)             printf("%s\n", str)
#define wws(k)               ww(k), putchar(' ')
#define inp(ar, n)           for (int ele = 0; ele < n; ele++)ar[ele] = read()
inline ll   read()           { ll sign = 1; ll x = 0; char ch; while (!isdigit(ch = getchar())) if (ch == '-') sign = -1; while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * sign;}
inline void wonl()           { putchar('\n');}
inline void ww(ll k)         { if (k < 0) putchar('-'), k *= -1; char ch[20]; int num = 0; while (k)ch[++num] = k % 10, k /= 10; if (num == 0) ch[++num] = 0; while (num)putchar(ch[num--] + '0');}

using namespace std;
const int N = 1e5 + 4;

template <typename T, typename... V>
inline void wonl(T t, V... v) {ww(t); if (sizeof...(v))putchar(' '); wonl(v...);}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    // _X_;
    // clock_t time_req = clock();

    int n = read(), p[n], a;
    inp(p, n);

    map<int, pii> pm;
    multiset<int> o[4];

    for (int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].F = a;
    }
    for (int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].S = a;
    }

    int m = read();
    while (m--) {
        a = read();
        if (o[a].size() == 0) {
            wws(-1);
            continue;
        }

        auto it = o[a].begin();

        wws(*it);

        int x = pm[*it].F, y = pm[*it].S;
        auto it1 = o[x].find(*it);
        auto it2 = o[y].find(*it);

        o[x].erase(it1), o[y].erase(it2);

    }

    // time_req = clock() - time_req;
    // cout << (float)time_req / CLOCKS_PER_SEC;
    return 0;
}


// Created by Priyanshu

#include <bits/stdc++.h>
#define M                    1000000007
#define pi                   3.14159265358979323846
#define ll                   long long
#define lld                  long double

// Pair
#define pii                  pair<int, int>
#define pll                  pair<ll, ll>

// Vector
#define vl                   vector<ll >
#define vi                   vector<int>
#define vpi                  vector<pii>
#define vpl                  vector<pll>
#define pb                   push_back
#define mp                   make_pair

// Search
#define lb                   lower_bound
#define ub                   upper_bound
#define mina                 *min_element
#define mama                 *max_element
#define bsrch                binary_search

////////
#define F                    first
#define S                    second
#define cel(x,a)             ((x + a - 1) / a)
#define all(v)               v.begin(), v.end()
#define lcm(m, n)            ((m / __gcd(m, n))*n)
#define deb(x)               cout << #x<<" = "<<x<<'\n'
#define ms(arr, v)           memset(arr, v, sizeof(arr))
#define ps(x,y)              fixed << setprecision(y) << x
#define X                  ios_base::sync_with_stdio(false); cin.tie(NULL)

// Input / Output
#define scn(str)             scanf("%s", str)
#define pri(str)             printf("%s\n", str)
#define wws(k)               ww(k), putchar(' ')
#define inp(ar, n)           for (int ele = 0; ele < n; ele++)ar[ele] = read()
inline ll   read()           { ll sign = 1; ll x = 0; char ch; while (!isdigit(ch = getchar())) if (ch == '-') sign = -1; while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * sign;}
inline void wonl()           { putchar('\n');}
inline void ww(ll k)         { if (k < 0) putchar('-'), k *= -1; char ch[20]; int num = 0; while (k)ch[++num] = k % 10, k /= 10; if (num == 0) ch[++num] = 0; while (num)putchar(ch[num--] + '0');}

using namespace std;
const int N = 1e5 + 4;

template <typename T, typename... V>
inline void wonl(T t, V... v) {ww(t); if (sizeof...(v))putchar(' '); wonl(v...);}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    // X;
    // clock_t time_req = clock();

    long long int n = read(), p[n], a;
    inp(p, n);

    map<long long int, pii> pm;
    multiset<long long int> o[4];

    for (long long int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].F = a;
    }
    for (long long int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].S = a;
    }

    int m = read();
    while (m--) {
        a = read();
        if (o[a].size() == 0) {
            wws(-1);
            continue;
        }

        auto it = o[a].begin();

        wws(*it);

        int x = pm[(*it)].F, y = pm[*it].S;
        auto it1 = o[x].find(*it);
        auto it2 = o[y].find(*it);

      if(x!=y){
        o[x].erase(*it1);

        o[y].erase(*it2);
      }
      else
         o[x].erase(*it1);

    }

    // time_req = clock() - time_req;
    // cout << (float)time_req / CLOCKS_PER_SEC;
    return 0;
}


// Created by Priyanshu

#include <bits/stdc++.h>
#define M                    1000000007
#define pi                   3.14159265358979323846
#define ll                   long long
#define lld                  long double

// Pair
#define pii                  pair<int, int>
#define pll                  pair<ll, ll>

// Vector
#define vl                   vector<ll >
#define vi                   vector<int>
#define vpi                  vector<pii>
#define vpl                  vector<pll>
#define pb                   push_back
#define mp                   make_pair

// Search
#define lb                   lower_bound
#define ub                   upper_bound
#define mina                 *min_element
#define mama                 *max_element
#define bsrch                binary_search

////////
#define F                    first
#define S                    second
#define cel(x,a)             ((x + a - 1) / a)
#define all(v)               v.begin(), v.end()
#define lcm(m, n)            ((m / __gcd(m, n))*n)
#define deb(x)               cout << #x<<" = "<<x<<'\n'
#define ms(arr, v)           memset(arr, v, sizeof(arr))
#define ps(x,y)              fixed << setprecision(y) << x
#define X                  ios_base::sync_with_stdio(false); cin.tie(NULL)

// Input / Output
#define scn(str)             scanf("%s", str)
#define pri(str)             printf("%s\n", str)
#define wws(k)               ww(k), putchar(' ')
#define inp(ar, n)           for (int ele = 0; ele < n; ele++)ar[ele] = read()
inline ll   read()           { ll sign = 1; ll x = 0; char ch; while (!isdigit(ch = getchar())) if (ch == '-') sign = -1; while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * sign;}
inline void wonl()           { putchar('\n');}
inline void ww(ll k)         { if (k < 0) putchar('-'), k *= -1; char ch[20]; int num = 0; while (k)ch[++num] = k % 10, k /= 10; if (num == 0) ch[++num] = 0; while (num)putchar(ch[num--] + '0');}

using namespace std;
const int N = 1e5 + 4;

template <typename T, typename... V>
inline void wonl(T t, V... v) {ww(t); if (sizeof...(v))putchar(' '); wonl(v...);}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    // X;
    // clock_t time_req = clock();

    long long int n = read(), p[n], a;
    inp(p, n);

    map<long long int, pii> pm;
    multiset<long long int> o[4];

    for (long long int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].F = a;
    }
    for (long long int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].S = a;
    }

    int m = read();
    while (m--) {
        a = read();
        if (o[a].size() == 0) {
            wws(-1);
            continue;
        }

        auto it = o[a].begin();

        wws(*it);

        int x = pm[(*it)].F, y = pm[*it].S;
        auto it1 = o[x].find(*it);
        auto it2 = o[y].find(*it);

        o[x].erase(*it1);

        o[y].erase(*it2);

    }

    // time_req = clock() - time_req;
    // cout << (float)time_req / CLOCKS_PER_SEC;
    return 0;
}


// Created by Priyanshu

#include <bits/stdc++.h>
#define M                    1000000007
#define pi                   3.14159265358979323846
#define ll                   long long
#define lld                  long double

// Pair
#define pii                  pair<int, int>
#define pll                  pair<ll, ll>

// Vector
#define vl                   vector<ll >
#define vi                   vector<int>
#define vpi                  vector<pii>
#define vpl                  vector<pll>
#define pb                   push_back
#define mp                   make_pair

// Search
#define lb                   lower_bound
#define ub                   upper_bound
#define mina                 *min_element
#define mama                 *max_element
#define bsrch                binary_search

////////
#define F                    first
#define S                    second
#define cel(x,a)             ((x + a - 1) / a)
#define all(v)               v.begin(), v.end()
#define lcm(m, n)            ((m / __gcd(m, n))*n)
#define deb(x)               cout << #x<<" = "<<x<<'\n'
#define ms(arr, v)           memset(arr, v, sizeof(arr))
#define ps(x,y)              fixed << setprecision(y) << x
#define _X_                  ios_base::sync_with_stdio(false); cin.tie(NULL)

// Input / Output
#define scn(str)             scanf("%s", str)
#define pri(str)             printf("%s\n", str)
#define wws(k)               ww(k), putchar(' ')
#define inp(ar, n)           for (int ele = 0; ele < n; ele++)ar[ele] = read()
inline ll   read()           { ll sign = 1; ll x = 0; char ch; while (!isdigit(ch = getchar())) if (ch == '-') sign = -1; while (isdigit(ch)) x = x * 10 + ch - '0', ch = getchar(); return x * sign;}
inline void wonl()           { putchar('\n');}
inline void ww(ll k)         { if (k < 0) putchar('-'), k *= -1; char ch[20]; int num = 0; while (k)ch[++num] = k % 10, k /= 10; if (num == 0) ch[++num] = 0; while (num)putchar(ch[num--] + '0');}

using namespace std;
const int N = 1e5 + 4;

template <typename T, typename... V>
inline void wonl(T t, V... v) {ww(t); if (sizeof...(v))putchar(' '); wonl(v...);}

///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

int main()
{
    // _X_;
    // clock_t time_req = clock();

    int n = read(), p[n], a;
    inp(p, n);

    map<int, pii> pm;
    multiset<int> o[4];

    for (int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].F = a;
    }
    for (int i = 0; i < n; i++) {
        a = read();
        o[a].insert(p[i]);
        pm[p[i]].S = a;
    }

    int m = read();
    while (m--) {
        a = read();
        if (o[a].size() == 0) {
            wws(-1);
            continue;
        }

        auto it = o[a].begin();

        wws(*it);

        int x = pm[*it].F, y = pm[*it].S;
        auto it1 = o[x].find(*it)
        o[x].erase(it1);
        auto it2 = o[y].find(*it);

       o[y].erase(it2);

    }

    // time_req = clock() - time_req;
    // cout << (float)time_req / CLOCKS_PER_SEC;
    return 0;
}


#include<bits/stdc++.h>

using namespace std;
long long int p[200005]={0};
  set<long long int>v1,v2,v3;
    set<long long int>::iterator it;

int main()
{
   long long int n,m,i,a,ans=1e10;

    cin>>n;
    for(i=0;i<n;i++){
        cin>>p[i];
    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            v1.insert(p[i]);
       else if(a==2)
            v2.insert(p[i]);
        else if(a==3)
            v3.insert(p[i]);

    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            v1.insert(p[i]);
        else if(a==2)
            v2.insert(p[i]);
        else if(a==3)
            v3.insert(p[i]);
    }
     cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>a;
        if(a==1)
        {
            if(v1.size()>0){

            it=v1.begin();
            ans=*it;
            cout<<ans<<" ";
            v1.erase(*it);
            v2.erase(*it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }

      else if(a==2)
        {
            if(v2.size()>0){

            it=v2.begin();
            ans=*it;
             cout<<ans<<" ";
            v1.erase(*it);
            v2.erase(*it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }
        else if(a==3)
        {
            if(v3.size()>0){

            it=v3.begin();
            ans=*it;
            cout<<ans<<" ";
            v1.erase(*it);
            v2.erase(*it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }
    }

    return 0;
}


#include<bits/stdc++.h>

using namespace std;
long long int p[200005]={0};
  set<long long int>v1,v2,v3;
    set<long long int>::iterator it;

int main()
{
   long long int n,m,i,a;

    cin>>n;
    for(i=0;i<n;i++){
        cin>>p[i];
    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            v1.insert(p[i]);
       else if(a==2)
            v2.insert(p[i]);
        else if(a==3)
            v3.insert(p[i]);

    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            v1.insert(p[i]);
        else if(a==2)
            v2.insert(p[i]);
        else if(a==3)
            v3.insert(p[i]);
    }
    cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>a;
        if(a==1)
        {
            if(v1.size()>0){

            it=v1.begin();
            cout<<*it<<" ";
            v1.erase(it);
            v2.erase(*it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }

      else if(a==2)
        {
            if(v2.size()>0){

            it=v2.begin();
             cout<<*it<<" ";
            v1.erase(*it);
            v2.erase(it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }
        else
        {
            if(v3.size()>0){

            it=v3.begin();
            cout<<*it<<" ";
            v1.erase(*it);
            v2.erase(*it);
            v3.erase(it);

        }
        else
            cout<<"-1"<<" ";
        }
    }

    return 0;
}


#include<bits/stdc++.h>
using namespace std;
set<long long int> s1,s2,s3;

set<long long int>::iterator it;
long long int p[200005];
int main()
{
    long long int n,i,x,m;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    for(i=0;i<n;i++)
        cin>>p[i];
    for(i=0;i<n;i++)
    {
        cin>>x;
        if(x==1)
            s1.insert(p[i]);
        else if(x==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);
    }

    for(i=0;i<n;i++)
    {
        cin>>x;
        if(x==1)
            s1.insert(p[i]);
        else if(x==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);
    }
    cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>x;
        if(x==1)
        {
            if(s1.size()>0)
            {
                it=s1.begin();
                cout<<*it<<" ";

                s2.erase(*it);
                s3.erase(*it);
                s1.erase(it);
            }
            else
                cout<<"-1 ";
        }

        else if(x==2)
        {
           if(s2.size()>0)
            {
                it=s2.begin();
                cout<<*it<<" ";

                s1.erase(*it);
                s3.erase(*it);
                s2.erase(it);
            }
            else
                cout<<"-1 ";
        }
        else
        {
            if(s3.size()>0)
            {
                it=s3.begin();
                cout<<*it<<" ";

                s2.erase(*it);
                s1.erase(*it);
                s3.erase(it);
            }
            else
                cout<<"-1 ";
        }
    }
    //cout<<s2.size();
    return 0;
}


#include<bits/stdc++.h>

using namespace std;

int main()
{
   long long int n,m,i,ans1,ans2,temp1,temp2;
    cin>>n;
    long long int p[n],a[n],b[n];
    for(i=0;i<n;i++){
        cin>>p[i];
    }
    for(i=0;i<n;i++){
        cin>>a[i];
    }
    for(i=0;i<n;i++){
        cin>>b[i];
    }
    cin>>m;
    long long int c[m];
    for(i=0;i<m;i++){
            cin>>c[i];
            ans1=1e12;
            ans2=1e12;
            temp1=0;
            temp2=0;
        for(int j=0;j<n;j++)
        {
            if(c[i]==a[j])
            {
                if(p[j]<ans1)
                {ans1=p[j];
                temp1=j;
                }
            }
            if(c[i]==b[j])
            {
                if(p[j]<ans2)
                {ans2=p[j];
                 temp2=j;
                }
            }

           }
         if(ans1==1e12 && ans2==1e12)
                {cout<<"-1"<<endl;}
       else {
        if(ans1>ans2)
       {
           cout<<ans2<<endl;
           b[temp2]=5;
           a[temp2]=5;
       }
       else{
        cout<<ans1<<endl;
        a[temp1]=5;
        b[temp1]=5;
       }
    }
    }
    return 0;
}


#include<bits/stdc++.h>

using namespace std;
long long int p[200005];
  set<long long int>s1,s2,s3;
    set<long long int>::iterator it;

int main()
{
    long long int n,m,i,a;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    for(i=0;i<n;i++){
        cin>>p[i];
    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            s1.insert(p[i]);
       else if(a==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);

    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            s1.insert(p[i]);
        else if(a==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);
    }
    cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>a;
        if(a==1)
        {
            if(s1.size()>0){

            it=s1.begin();
            cout<<*it<<" ";
            s3.erase(*it);
            s2.erase(*it);
            s1.erase(*it);

        }
        else
            cout<<"-1 ";
        }

      else if(a==2)
        {
            if(s2.size()>0){

            it=s2.begin();
             cout<<*it<<" ";
            s1.erase(*it);
            s3.erase(*it);
            s2.erase(*it);

        }
        else
            cout<<"-1 ";
        }
        else
        {
            if(s3.size()>0){

            it=s3.begin();
            cout<<*it<<" ";
            s1.erase(*it);
            s2.erase(*it);
            s3.erase(*it);

        }
        else
            cout<<"-1 ";
        }
    }

    return 0;
}


#include<bits/stdc++.h>

using namespace std;
long long int p[200005];
  set<long long int>s1,s2,s3;
    set<long long int>::iterator it;

int main()
{
    long long int n,m,i,a;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    for(i=0;i<n;i++){
        cin>>p[i];
    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            s1.insert(p[i]);
       else if(a==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);

    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            s1.insert(p[i]);
        else if(a==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);
    }
    cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>a;
        if(a==1)
        {
            if(s1.size()>0){

            it=s1.begin();
            cout<<*it<<" ";
            s1.erase(it);
            s2.erase(*it);
            s3.erase(*it);

        }
        else
            cout<<"-1 ";
        }

      else if(a==2)
        {
            if(s2.size()>0){

            it=s2.begin();
             cout<<*it<<" ";
            s1.erase(*it);
            s2.erase(it);
            s3.erase(*it);

        }
        else
            cout<<"-1 ";
        }
        else
        {
            if(s3.size()>0){

            it=s3.begin();
            cout<<*it<<" ";
            s1.erase(*it);
            s2.erase(*it);
            s3.erase(it);

        }
        else
            cout<<"-1 ";
        }
    }

    return 0;
}


#include<bits/stdc++.h>

using namespace std;
long long int p[200005]={0};
  set<long long int>v1,v2,v3;
    set<long long int>::iterator it;

int main()
{
    long long int n,m,i,a;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    for(i=0;i<n;i++){
        cin>>p[i];
    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            v1.insert(p[i]);
       else if(a==2)
            v2.insert(p[i]);
        else if(a==3)
            v3.insert(p[i]);

    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            v1.insert(p[i]);
        else if(a==2)
            v2.insert(p[i]);
        else if(a==3)
            v3.insert(p[i]);
    }
    cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>a;
        if(a==1)
        {
            if(v1.size()>0){

            it=v1.begin();
            cout<<*it<<" ";
            v1.erase(*it);
            v2.erase(*it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }

      else if(a==2)
        {
            if(v2.size()>0){

            it=v2.begin();
             cout<<*it<<" ";
            v1.erase(*it);
            v2.erase(*it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }
        else
        {
            if(v3.size()>0){

            it=v3.begin();
            cout<<*it<<" ";
            v1.erase(*it);
            v2.erase(*it);
            v3.erase(*it);

        }
        else
            cout<<"-1"<<" ";
        }
    }

    return 0;
}


#include<bits/stdc++.h>

using namespace std;
long long int p[200005];
  set<long long int>s1,s2,s3;
    set<long long int>::iterator it;

int main()
{
    long long int n,m,i,a;
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cin>>n;
    for(i=0;i<n;i++){
        cin>>p[i];
    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            s1.insert(p[i]);
       else if(a==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);

    }
    for(i=0;i<n;i++){
        cin>>a;
        if(a==1)
            s1.insert(p[i]);
        else if(a==2)
            s2.insert(p[i]);
        else
            s3.insert(p[i]);
    }
    cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>a;
        if(a==1)
        {
            if(s1.size()>0){

            it=s1.begin();
            cout<<*it<<" ";
            s3.erase(it);
            s2.erase(*it);
            s1.erase(*it);

        }
        else
            cout<<"-1 ";
        }

      else if(a==2)
        {
            if(s2.size()>0){

            it=s2.begin();
             cout<<*it<<" ";
            s1.erase(*it);
            s3.erase(*it);
            s2.erase(*it);

        }
        else
            cout<<"-1 ";
        }
        else
        {
            if(s3.size()>0){

            it=s3.begin();
            cout<<*it<<" ";
            s1.erase(*it);
            s2.erase(*it);
            s3.erase(*it);

        }
        else
            cout<<"-1 ";
        }
    }

    return 0;
}


#include <iostream>
#include <set>
using namespace std;
int main()
{
	set<int>s[4];
	int n;
	cin>>n;
	int p[n],a[n],b[n];
	for(int i=0;i<n;i++)
	{
		cin>>p[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
		s[a[i]].insert(p[i]);
	}
	for(int i=0;i<n;i++)
	{
		cin>>b[i];
		s[b[i]].insert(p[i]);
	}
	int m;
	cin>>m;
	int c;
	set<int>::iterator it;
	for(int i=0;i<m;i++)
	{
		cin>>c;
		it=s[c].begin();
		int k=*it;
		if(k==0){cout<<-1<<" ";}
		else{cout<<k<<" ";}
		s[1].erase(*it);
		s[2].erase(*it);
		s[3].erase(*it);

	}
	cout<<endl;

}


#include <iostream>
using namespace std;
#define SIZE 1000000000
int main()
{
	int n;
	cin>>n;
	int p[n],a[n],b[n];
	for(int i=0;i<n;i++)
	{
		cin>>p[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>b[i];
	}
	int m;
	cin>>m;
	int c[m+1];
	for(int i=0;i<m;i++)
	{

		cin>>c[i];
		int minm=SIZE;
		int store=m;
		int ans=0;
		for(int j=0;j<n;j++)
		{
			if(c[i]==a[j] || c[i]==b[j])
			{
				ans=1;
				if(p[j]<minm)	{store=j;  minm=p[j];			}

			}
		}
		if(ans==1){cout<<minm<<" ";
		a[store]=0;b[store]=0;}
		else{cout<<-1<<" ";}

	}

}


#include <iostream>
using namespace std;
#define SIZE 1000000000
int main()
{
	int n;
	cin>>n;
	int p[n],a[n],b[n];
	for(int i=0;i<n;i++)
	{
		cin>>p[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>b[i];
	}
	int m;
	cin>>m;
	int c[m];
	for(int i=0;i<m;i++)
	{

		cin>>c[i];
		int minm=SIZE;
		int store;
		int ans=0;
		for(int j=0;j<n;j++)
		{
			if(c[i]==a[j] || c[i]==b[j])
			{
				ans=1;
				if(p[j]<minm)	{store=j;  minm=p[j];			}

			}
		}
		if(ans==1){cout<<minm<<" ";
		a[store]=0;b[store]=0;}
		else{cout<<-1<<" ";}

	}

}


#include <iostream>
using namespace std;
#define SIZE 1000000000
int main()
{
	int n;
	cin>>n;
	int p[n+1],a[n+1],b[n+1];
	for(int i=0;i<n;i++)
	{
		cin>>p[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>a[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>b[i];
	}
	int m;
	cin>>m;
	int c[m];
	for(int i=0;i<m;i++)
	{

		cin>>c[i];
		int minm=SIZE;
		int store=n;
		int ans=0;
		for(int j=0;j<n;j++)
		{
			if(c[i]==a[j] || c[i]==b[j])
			{
				ans=1;
				if(p[j]<minm)	{store=j;  minm=p[j];			}

			}
		}
		if(ans==1){cout<<minm<<" ";
		a[store]=0;b[store]=0;}
		else{cout<<-1<<" ";}

	}

}


#include <iostream>
#include <set>
using namespace std;
int main()
{
	set<int>s[4];
	int n;
	cin>>n;
	int p[200010],a,b;
	for(int i=0;i<n;i++)
	{
		cin>>p[i];
	}
	for(int i=0;i<n;i++)
	{
		cin>>a;
		s[a].insert(p[i]);
	}
	for(int i=0;i<n;i++)
	{
		cin>>b;
		s[b].insert(p[i]);
	}
	int m;
	cin>>m;
	int c;
	set<int>::iterator it;
	for(int i=0;i<m;i++)
	{
		cin>>c;
		it=s[c].begin();
		int k=*it;
		if(k==0){cout<<-1<<" ";}
		else{cout<<k<<" ";}
		s[1].erase(k);
		s[2].erase(k);
		s[3].erase(k);

	}
	cout<<endl;

}


n=int(input())
l=[]
for i in range (n):
    x=int(input())
    y=input()
    p=y.find("8")

    if x-(p+1)>=11 and p!=0:

        l.append("YES")
    else :
        l.append("NO")

for i in l:
    print(i)


n=int(input())
l=[]
for i in range (n):
    x=int(input())
    y=input()
    p=y.find("8")

    if x-(p+1)>=11 and p!=0:

        l.append("YES")
    elif :
        l.append("NO")

for i in l:
    print(i)


n=int(input())
l=[]
p=-1
for i in range (n):
    x=int(input())
    y=input()
    p=y.find("8")

    if x-(p+1)>=11 and p!=-1:

        l.append("YES")
    else :
        l.append("NO")

for i in l:
    print(i)


import math
import sys
import bisect
#input=sys.stdin.readline
t=int(input())
#t=1
for _ in range(t):
    #mod=10**9+7
    n=int(input())
    #n,k=map(int,input().split())
    #l=list(map(int,input().split()))
    s=input()
    pos=-1
    for i in range(n):
        if s[i]=='8':
            pos=i
            break
    if pos==-1 or (n-pos)<11:
        print("NO")
    else:
        print("YES")


import math as mt
import sys
import bisect
#input=sys.stdin.readline
t=int(input())
#t=1
for _ in range(t):
    #mod=10**9+7
    n=int(input())
    #n,k=map(int,input().split())
    #l=list(map(int,input().split()))
    s=input()
    pos=-1
    for i in range(n):
        if s[i]=='8':
            pos=i
    if pos==-1 or n-pos>11:
        print("NO")
    else:
        print("YES")


import math as mt
import sys
import bisect
#input=sys.stdin.readline
t=int(input())
#t=1
for _ in range(t):
    #mod=10**9+7
    n=int(input())
    #n,k=map(int,input().split())
    #l=list(map(int,input().split()))
    s=input()
    pos=-1
    for i in range(n):
        if s[i]=='8':
            pos=i
            break
    if pos==-1 or n-pos<11:
        print("NO")
    else:
        print("YES")


t = int(input())
for T in range(t):
	l = int(input())
	s = input()
	try:
		x = s.index('8')
	except:
		x = 'NO'
	lx = l - x

	if x == 'NO':
		print(x)
	else:
		if l < 11:
			print('NO')
		elif l == 11:
			if s[0] == 8:
				print('YES')
			else:
				print('NO')
		else:
			if lx >= 11:
				print('YES')
			else:
				print('NO')


t = int(input())
for T in range(t):
	l = int(input())
	s = input()
	try:
		x = s.index('8')
		lx = l - x
	except:
		x = 'NO'

	if x == 'NO':
		print(x)
	else:
		if l < 11:
			print('NO')
		elif l == 11:
			if s[0] == 8:
				print('YES')
			else:
				print('NO')
		else:
			if lx >= 11:
				print('YES')
			else:
				print('NO')


t = int(input())
for T in range(t):
	l = int(input())
	s = input()
	x = s.index('8')
	lx = l - x

	if l < 11:
		print('NO')
	elif l == 11:
		if s[0] == 8:
			print('YES')
		else:
			print('NO')
	else:
		if lx >= 11:
			print('YES')
		else:
			print('NO')


t = int(input())
for T in range(t):
	l = int(input())
	s = input()
	try:
		x = s.index('8')
		lx = l - x
	except:
		x = 'NO'

	if x == 'NO':
		print(x)
	else:
		if l < 11:
			print('NO')
		elif l == 11:
			if s[0] == '8':
				print('YES')
			else:
				print('NO')
		else:
			if lx >= 11:
				print('YES')
			else:
				print('NO')


from itertools import dropwhile

if __name__ == '__main__':
    for _ in range(int(input())):
        n = int(input())
        if len(list(dropwhile(lambda x: x != '8',input()))) >= 11:
            print("YES")
        else:
            print("NO")


from itertools import dropwhile

if __name__ == '__main__':
    for _ in range(int(input())):
        n = int(input())
        if len(dropwhile(lambda x: x != '8',list(input()))) >= 11:
            print("YES")
        else:
            print("NO")


from itertools import dropwhile

if __name__ == '__main__':
    for _ in range(int(input())):
        n = int(input())
        if len(dropwhile(lambda x: x != '8',input())) >= 11:
            print("YES")
        else:
            print("NO")


for t in range(int(input())):
    n=int(input())
    s=input()
    if n==1 and s[0]=='8':
        print("YES")
    else:
        i=0
        j=i
        while n>11:
            if s[i]!='8':
                i+=1
                n-=1
            else:
                j=i
                i+=1
        print("YES" if s[j]=='8' and n==11 else "NO")


for t in range(int(input())):
    n=int(input())
    s=input()
    i=0
    while i<n-5 and s[i]!='8':
        i+=1
    print("YES" if s[i]=='8' and n-i>=11 else "NO")


for t in range(int(input())):
    n=int(input())
    s=input()
    if n==1 and s[0]=='8':
        print("YES")
    else:
        m=n
        i=0
        j=i
        while n>11 and i<m:
            if s[i]!='8':
                i+=1
                n-=1
            else:
                j=i
                break;
        print("YES" if s[j]=='8' and n-j>=11 else "NO")


for t in range(int(input())):
    n=int(input())
    s=input()
    if n==1 and s[0]=='8':
        print("YES")
    else:
        m=n
        i=0
        j=i
        while n>11 and i<m:
            if s[i]!='8':
                i+=1
                n-=1
            else:
                j=i
                break;
        print("YES" if s[j]=='8' and n>=11 else "NO")


for t in range(int(input())):
    n=int(input())
    s=input()
    if n==1 and s[0]=='8':
        print("YES")
    else:
        m=n
        i=0
        j=i
        while n>11 and i<m:
            if s[i]!='8':
                i+=1
                n-=1
            else:
                j=i
                break;
        print("YES" if s[j]=='8' and m-j>=11 else "NO")


n=int(input())
for i in range(n):
    l=int(input())
    s=input()
    if(l>=11):
        if(l==11 and s[0]=='8'):
            print("YES")
        elif(l>11):
            if '8' in s[0:(l-11+1)]:
                print("YES")
            else:
                print("NO")
        else:
            print("NO")
    else:
        print("NO")


n=int(input())
for i in range(n):
    l=int(input())
    s=input()
    if(l>=11):
        if(l==11 and s[0]==8):
            print("YES")
        elif(l>11):
            if '8' in s[0:(l-11+1)]:
                print("YES")
            else:
                print("NO")
        else:
            print("NO")
    else:
        print("NO")


n=int(input())
for i in range(n):
    l=int(input())
    s=input()
    if(len(s)<11):
        print("NO")
    elif(len(s)==11 and s[0]=='8'):
        print("YES")
    elif(len(s)>11):
        s1=s[:len(s)-11]
        if '8' in s1:
            print("YES")
        else:
            print("NO")
    else:
        print("NO")


t = int(input())
for i in range(t):
    n = int(input())
    s = input()
    while i < n and s[i] != '8':
        i+=1
    if (n-i)>=11:
        print('YES')
    else:
        print('NO')


t = int(input())
for i in range(t):
    n = int(input())
    s = input()
    i = 0
    while i < n and s[i] != '8':
        i+=1
    if (n-i)>=11:
        print('YES')
    else:
        print('NO')


t = int(input())
for i in range(t):
    n = int(input())
    s = input()
    while i < n and s[i] != '8':
        i+=1
    if (n-i)>11:
        print('YES')
    else:
        print('NO')


t = int(input())
ans = []
for i in range(t):
    n = int(input())
    s = input()
    ind = len(s)
    if '8' in s:
        ind = s.index('8')
    if ind > 0 and len(s) - ind - 1 >= 11:
        ans.append("YES")
    else:
        ans.append("NO")

for i in ans:
    print(i)


t = int(input())
ans = []
for i in range(t):
    n = int(input())
    s = input()
    ind = len(s)
    if '8' in s:
        ind = s.index('8')
    if ind < len(s) and len(s) - ind >= 11:
        ans.append("YES")
    else:
        ans.append("NO")

for i in ans:
    print(i)


for _ in range (int(input())) :
    n = int(input())
    s = input()
    ans = s.find('8')
    if n - ans - 1 < 11 or ans == -1 : print('NO')
    else : print('YES')


for _ in range (int(input())) :
    n = int(input())
    s = input()
    ans = s.find('8')
    if n - ans  < 11 or ans == -1 : print('NO')
    else : print('YES')


for _ in range(int(input()):
    n=int(input())
    s=input()
    if '8' in s[:-10]:
        print('YES')
    else:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    s=input()
    if '8' in s[:-10]:
        print('YES')
    else:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    s=input();count=0
    t=len(s)-11
    if s[0]=='8':
        print('YES')
        count=1
    else:
        for i in s[0:t]:
            if i=='8':
                count=1
                print('YES')
                break
    if count==0:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    s=input();count=0
    t=len(s)-11
    for i in s[0:t]:
        if i=='8':
            count=1
            print('YES')
            break
    if count==0:
        print("NO")


n=int(input())
s=input();count=0
t=len(s)-11
for i in s[0:t]:
    if i=='8':
        count=1
        print('Yes')
        break
if count==0:
    print("No")


for _ in range(int(input())):
    n=int(input())
    s=input()
    count=0
    for i in range(len(s)):
        if s[i]=='8':
            count=i
            break
    if abs(n-count+1)>=10:
        print('YES')
    else:
        print('NO')


for _ in range(int(input())):
    n=int(input())
    s=input();count=0
    t=len(s)-11
    if s[0]=='8':
        print('YES')
        count=1
    else:
        for i in s[t:]:
            if i=='8':
                count=1
                print('YES')
                break
    if count==0:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    s=input()
    count=0
    for i in range(len(s)):
        if s[i]=='8':
            break
        count=i

    if abs(n-count+2)>=10:
        print('YES')
    else:
        print('NO')


for _ in range(int,input().split()):
    n=int(input())
    s=input()
    if '8' in s[:-10]:
        print('YES')
    else:
        print("NO")


q=int(input())
for i in range(q):
    l=int(input())
    s=input()
   # print(l)

    if(l<11):
        print('NO')
    else:
        a=l-11
        flag=0
        for i  in range(a+1):
            if(s[i]=='8'):
                flag=1
                break
        if(flag==1):
            print('YES')
        else:
            print('NO')


q=int(input())
for i in range(q):
    l=int(input())
    s=input()

    if(l<11):
        print('NO')
    else:
        a=l-11
        flag=0
        for i in range(a):
            if(s[i]=='8'):
                flag=1
                break
        if(flag==1):
            print('YES')


q=int(input())
for i in range(q):
    s=input()
    l=len(s)
    if(l<11):
        print('NO')
    else:
        a=l-11
        flag=0
        for i in range(a):
            if(s[i]=='8':
                flag=1
                break
        if(flag==1):
            print('YES')


q=int(input())
for i in range(q):
    l=int(input())
    s=input()

    if(l<11):
        print('NO')
    else:
        a=l-11
        flag=0
        for i in range(a):
            if(s[i]=='8'):
                flag=1
                break
        if(flag==1):
            print('YES')
        else:
            print('NO')


for i in range(int(input())):
    n,s=int(input()),input()
    print(['NO','YES']['8' in s[:-10]])


for i in range(int(input())):
    n,s=int(input()),input()
    print(['NO','YES']['8' in s[:n-11]])


for i in range(int(input())):
    n,s=int(input()),input()
    print(['NO','YES'][int('8' in s[:n-10])])


for i in range(int(input())):
    n,s=int(input()),input()
    if i==9:
        print(s)
    print(['NO','YES']['8' in s[:n-10]])


for i in range(int(input())):
    n,s=int(input()),input()
    print(['NO','YES'][ '8' in s[:len(s)-10]])


for i in range(int(input())):
    n,s=int(input()),input()
    print(['NO','YES']['8' in s[:n-9]])


for i in range(int(input())):
    n,s=int(input()),input()
    print(['NO','YES'][ '8' in s[:n-10]])


no_of_test_case=int(input())
noLength=11
flag=False
while no_of_test_case!=0:
    no_of_test_case-=1
    no_string=input()
    flag=False
    """we are trying to iteratre window length of 11 and if we find some thing stating with 8 we find a no
    """
    for i in range(0,(len(no_string)-(noLength-1))):
        if no_string[i] =='8':
            flag=True
    if flag:
        print("No")
    else:
        print("Yes")


import copy
no_of_test_case=int(input())
noLength=11
while no_of_test_case!=0:
    input()
    no_string=input()
    #print(no_string,no_of_test_case)
    no_of_test_case-=1
    if len(no_string)<11:
        print('No')
        continue
    elif len(no_string)==11:
        if no_string[0]=="8":
            print("Yes")
        else:
            print("No")
        continue
    else:

        #print(no_string,"\n&&&&&&&&&&&&&&&&&&&&&&&&")
        flag=False
        no_string=list(no_string)
        no_string=list(map(int,no_string))
        No_copy=copy.copy(no_string)
        no_string.sort(reverse=True)
        i=0
        no_index=dict()
        for j in range(0,10):
            no_index[j]=0
        while no_string[i]>=7 and i <len(no_string)-1:
            no_index[no_string[i]]+=1
            i+=1
        #print(no_string,'the dixtionary is',no_index)
        # now check that last how much 8 is in last 10 biths
        end_string=No_copy[-10:]
        lasteight=0
        for elem in end_string:
            if elem==8:
                lasteight+=1
        if no_index[8]>lasteight:
            print('Yes')
        else:
            print('No')


no_of_test_case=int(input())
noLength=11
flag=False
while no_of_test_case!=0:
    no_of_test_case-=1
    no_string=input()
    flag=False
    """we are trying to iteratre window length of 11 and if we find some thing stating with 8 we find a no
    """
    for i in range(0,(len(no_string)-(noLength-1))):
        if no_string[i] =='8':
            flag=True
            break
    if flag:
        print("No")
    else:
        print("Yes")


import copy
no_of_test_case=int(input())
noLength=11
while no_of_test_case!=0:
    input()
    no_string=input()
    #print(no_string,no_of_test_case)
    no_of_test_case-=1
    if len(no_string)<11:
        print('No')
        continue
    elif len(no_string)==11:
        if no_string[0]=="8":
            print("Yes")
        else:
            print("No")
        continue
    else:

        #print(no_string,"\n&&&&&&&&&&&&&&&&&&&&&&&&")
        flag=False
        no_string=list(no_string)
        no_string=list(map(int,no_string))
        No_copy=copy.copy(no_string)
        no_string.sort(reverse=True)
        i=0
        no_index=dict()
        for j in range(0,10):
            no_index[j]=0
        while no_string[i]>=7 and i <len(no_string):
            no_index[no_string[i]]+=1
            i+=1
        #print(no_string,'the dixtionary is',no_index)
        # now check that last how much 8 is in last 10 biths
        end_string=No_copy[-10:]
        lasteight=0
        for elem in end_string:
            if elem==8:
                lasteight+=1
        if no_index[8]>lasteight:
            print('Yes')
        else:
            print('No')


no_of_test_case=int(input())
noLength=11
flag=False
while no_of_test_case!=0:
    no_of_test_case-=1
    no_string=input()
    flag=False
    """we are trying to iteratre window length of 11 and if we find some thing stating with 8 we find a no
    """
    for i in range(0,(len(no_string)-(noLength-1))):
        if no_string[i] =='8':
            flag=True
    if flag:
        print("Yes")
    else:
        print("No")


#------------------------------warmup----------------------------
# *******************************
# * AUTHOR:  RAJDEEP GHOSH      *
# * NICK  :  Rajdeep2k          *
# * INSTITUTION: IIEST, SHIBPUR *
# *******************************
import os
import sys
from io import BytesIO, IOBase
import math
from fractions import Fraction
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#-------------------game starts now---------------------------------------------------
for i in range(int(input())):
    n=int(input())
# l=list(map(int,input().split()))
    s=input()
    if '8' not in s:
        print('NO')
    else:
        f=True
        for i in range(n):
            if s[i]=='8' and i+10<n:
                print('YES')
                f=False
                break
        if f:
            print('NO')


#------------------------------warmup----------------------------
# *******************************
# * AUTHOR:  RAJDEEP GHOSH      *
# * NICK  :  Rajdeep2k          *
# * INSTITUTION: IIEST, SHIBPUR *
# *******************************
import os
import sys
from io import BytesIO, IOBase
import math
from fractions import Fraction
BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None

    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()

    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()

    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)

class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")

#-------------------game starts now---------------------------------------------------
for i in range(int(input())):
    n=int(input())
# l=list(map(int,input().split()))
    s=input()
    if '8' not in s:
        print('NO')
    else:
        f=True
        for i in range(n):
            if s[i]=='8' and i+10<=n:
                print('YES')
                f=False
                break
        if f:
            print('NO')


for i in range(int(input()))"
    n = int(input())
    s = input()
    count = 0
    for i in s:
        if i == "8":
            break
        count += 1
    if (n - count >= 11):
        print("YES")
    else:
        print("NO")


for i in range(int(input())):
    n = int(input())
    s = input()
    count = 0
    for i in s:
        if i == "8":
            break
        count += 1
    if (n - count >= 11):
        print("YES")
    else:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    s=input()
    if "8" in s:
        a=s.index("8")
        if n-a-11>=11:
            print("YES")
        else:
            print("NO")
    else:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    s=input()
    if "8" in s:
        a=s.index("8")
        if n-a>=11:
            print("YES")
        else:
            print("NO")
    else:
        print("NO")


for _ in range(int(input())):
    n=int(input())
    s=input()
    if "8" in s:
        a=s.index("8")
        if n-a-1>=11:
            print("YES")
        else:
            print("NO")
    else:
        print("NO")


n = int(input())
for nn in range(n):
    str_length = int(input())
    number = list(input())
    count = 0
    flag = False
    for index in range(str_length):
        if number[index] == "8":
            if len(number[index + 1:]) > 7:
                flag = True
                break
    if flag:
        print("YES")
    else:
        print("NO")


n = int(input())
for nn in range(n):
    str_length = int(input())
    number = list(input())
    count = 0
    flag = False
    for index in range(str_length):
        if number[index] == "8":
            if len(number[index + 1:]) > 9:
                flag = True
                break
    if flag:
        print("YES")
    else:
        print("NO")


n = int(input())
for nn in range(n):
    str_length = int(input())
    number = list(input())
    count = 0
    flag = False
    for index in range(str_length):
        if number[index] == "8":
            if str_length - index > 10:
                flag = True
                break
    if flag:
        print("YES")
    else:
        print("NO")


n = int(input())
for nn in range(n):
    str_length = int(input())
    number = list(input())
    count = 0
    flag = False
    for index in range(str_length):
        if number[index] == "8":
            if len(number[index + 1:]) > 6:
                flag = True
                break
    if flag:
        print("YES")
    else:
        print("NO")


    t=int(input())
    for i in range(t):
        n=int(input())
        a=input()
        c=n-a.find("8")
        if "8" in a and c>=11:
            print("YES")
        else:
            print("NO")


t=int(input()
for i in range(t):
    n=int(input())
    a=input()
    c=n-a.find("8")
    if "8" in a and c>=11:
        print("YES")
    else:
        print("NO")


t=int(input())
for i in range(t):
    n=int(input())
    a=input()
    c=n-a.find("8")
    if "8" in a and c>=11:
        print("YES")
    else:
        print("NO")


t=int(input())
for i in range(t):
    n=int(input())
    a=input()
    c=n-a.find("8")
    if c>=11:
        print("YES")
    else:
        print("NO")


def fun1(num, an):
    if an > 11:
        ind = num.find('8')
        return print('YES') if an - ind >= 11 and ind >= 0 else print('NO')
    else:
        return print('YES') if num[0] == '8' else print('NO')

def sol():
    totaln = int(input())
    nums, ns = [], []
    for _ in range(totaln):
        ns.append(int(input()))
        nums.append(input())

    for i in range(totaln):
        if i >= 8:
            print(nums[i])
        fun1(nums[i], ns[i])

if __name__ == "__main__":
    sol()


def fun1(num, an):
    if an > 11:
        ind = num.index('8')
        print('YES') if an - ind >= 11 else print('NO')
    elif an < 11:
        print("NO")
    else:
        print('YES') if num[0] == '8' else print('NO')
    pass

def sol():
    totaln = int(input())
    nums, ns = [], []
    for _ in range(totaln):
        ns.append(int(input()))
        nums.append(input())

    for i in range(totaln):
        fun1(nums[i], ns[i])

if __name__ == "__main__":
    sol()


def fun1(num, an):
    if an > 11:
        ind = num.find('8')
        return print('YES') if an - ind >= 11 and ind >= 0 else print('NO')
    else:
        return print('YES') if num[0] == '8' else print('NO')

def sol():
    totaln = int(input())
    nums, ns = [], []
    for _ in range(totaln):
        ns.append(int(input()))
        nums.append(input())

    for i in range(totaln):
        fun1(nums[i], ns[i])

if __name__ == "__main__":
    sol()


def fun1(num, an):
    if an > 11:
        ind = num.find('8')
        return print('YES') if an - ind >= 11 and ind >= 0 else print('NO')
    elif an < 11:
        print('NO')
    else:
        return print('YES') if num[0] == '8' else print('NO')

def sol():
    totaln = int(input())
    nums, ns = [], []
    for _ in range(totaln):
        ns.append(int(input()))
        nums.append(input())

    for i in range(totaln):
        fun1(nums[i], ns[i])

if __name__ == "__main__":
    sol()


array = []
for i in range (int(input())):
    n = int(input())
    s = input()
    if n == 11:
        if s[0] == "8":
            array += ["YES"]
        else:
            array += ["NO"]
    else:
        for i in range (n - 9):
            if i == n - 10:
                array += ["NO"]
            if s[i] == "8":
                array += ["YES"]
                break
            if s[i] != "8":
                continue

for i in array:
    print(i)


array = []
for i in range (int(input())):
    n = int(input())
    s = input()
    stts = False
    for i in range (n):
        if n - i >= 11:
            if s[i] == "8":
                print("YES")
                break
        else:
            print("NO")
            break


array = []
for i in range (int(input())):
    n = int(input())
    s = input()
    if n == 11:
        if s[0] == "8":
            array += ["YES"]
        else:
            array += ["NO"]
    else:
        for i in range (n - 10):
            if i == n - 11:
                array += ["NO"]
            if s[i] == "8":
                array += ["YES"]
                break
            if s[i] != "8":
                continue

for i in array:
    print(i)


n = int(input())

for i in range(n):
    k = int(input())
    l = input()
    n = l[:-10]
    if k<11:
        print("NO")
    elif l.count("8") == 0:
        print("NO")
    elif n.count("8"):
        print("YES")


n = int(input())

for i in range(n):
    k=max(int(input())-10, 0)
    l=input()
    n=l[:k]

    if n.count("8"):
        print("YES")
    else:
        print("NO")


n = int(input())

for i in range(n):
    k = int(input())
    l = input()
    n = l[:k-10]
    if k<11:
        print("NO")
    elif l.count("8") == 0:
        print("NO")
    elif n.count("8"):
        print("YES")


for i in range(int(input())):
    n=int(input())
    s=input()
    c=0
    if "8" in s:
        if n-s.index("8")>=11:
            print(n-s.index("8"))
            print("YES")
            c=1
    if(c==0):
        print("NO")


for i in range(int(input())):
    n=int(input())
    s=input()
    c=0
    if "8" in s:
        if n-s.index("8")>=11:
            # print(n-s.index("8"))
            print("YES")
            c=1
    if(c==0):
        print("NO")


for l in range(int(input()):
    n=int(input())
    s=str(input())
    flag=True
    for i in range(n):
        if(s[i]=='8'):
            if(n-i>=11):
                flag=False
                break
    if(flag==False):
        print("YES")
    else:
        print("NO")


for l in range(int(input())):
    n=int(input())
    s=str(input())
    flag=True
    for i in range(n):
        if(s[i]=='8'):
            if(n-i>=11):
                flag=False
                break
    if(flag==False):
        print("YES")
    else:
        print("NO")


for i in range(int(input())):
	p=int(input())
	if p<11:
		print("NO")
	else:
		s=input()

		temp1=s.find('8')
		if temp1==-1:
			print("NO")
		else:
			print("YES")


for i in range(int(input())):
	p=int(input())
	if p<11:
		print("NO")
	else:
		s=input()

		temp1=s.find('8')
		if temp1==-1:
			print("NO")
		else:
			if p-(temp1+1)>=11:
				print("YES")
			else:
				print("NO")


def MaxOneOrZero(n, word):
        result = ""
        if(word.__contains__('o') and word.__contains__('n') and word.__contains__('e')):
            cant = [word.count('o'), word.count('n'), word.count('e')]
            num = min(cant)
            for _ in range(num):
                    if(result == ""):
                        result += "1"
                    else:
                        result += " 1"

        if(word.__contains__('z') and word.__contains__('e') and word.__contains__('r') and word.__contains__('o')):
            cant = [word.count('z'), word.count('e'), word.count('r'), word.count('o')]
            num = min(cant)

            for _ in range(num):
                    if(result == ""):
                        result += "0"
                    else:
                        result += " 0"

        return result

def createNumberPhone(n,s):
    for i in range(n):
        if(len(s) < 11):
            print('NO')
            break
        if(s.startswith('8') and len(s) == 11):
            print('YES')
        if(s.startswith('8')):
            s = s[0:-2]
        else:
            s = s[1:-1]

t = int(input())
n = []
s = []
for i in range(t):
    n = int(input())
    s = input()
    createNumberPhone(n,s)


def MaxOneOrZero(n, word):
        result = ""
        if(word.__contains__('o') and word.__contains__('n') and word.__contains__('e')):
            cant = [word.count('o'), word.count('n'), word.count('e')]
            num = min(cant)
            for _ in range(num):
                    if(result == ""):
                        result += "1"
                    else:
                        result += " 1"

        if(word.__contains__('z') and word.__contains__('e') and word.__contains__('r') and word.__contains__('o')):
            cant = [word.count('z'), word.count('e'), word.count('r'), word.count('o')]
            num = min(cant)

            for _ in range(num):
                    if(result == ""):
                        result += "0"
                    else:
                        result += " 0"

        return result

def createNumberPhone(n,s):
    for i in range(n):
        print(s)
        if(len(s) < 11):
            print('NO')
            break
        if(s.startswith('8') and len(s) == 11):
            print('YES')
            break
        if(s.startswith('8')):
            s = s[:-1]
        else:
            s = s[1:]

t = int(input())
n = []
s = []
for i in range(t):
    n = int(input())
    s = input()
    createNumberPhone(n,s)


def MaxOneOrZero(n, word):
        result = ""
        if(word.__contains__('o') and word.__contains__('n') and word.__contains__('e')):
            cant = [word.count('o'), word.count('n'), word.count('e')]
            num = min(cant)
            for _ in range(num):
                    if(result == ""):
                        result += "1"
                    else:
                        result += " 1"

        if(word.__contains__('z') and word.__contains__('e') and word.__contains__('r') and word.__contains__('o')):
            cant = [word.count('z'), word.count('e'), word.count('r'), word.count('o')]
            num = min(cant)

            for _ in range(num):
                    if(result == ""):
                        result += "0"
                    else:
                        result += " 0"

        return result

def createNumberPhone(n,s):
    for i in range(n):
        if(len(s) < 11):
            print('NO')
            break
        if(s.startswith('8') and len(s) == 11):
            print('YES')
            break
        if(s.startswith('8')):
            s = s[0:-2]
        else:
            s = s[1:-1]

t = int(input())
n = []
s = []
for i in range(t):
    n = int(input())
    s = input()
    createNumberPhone(n,s)


def createNumberPhone(n,s):
    for _ in range(n):
        if(len(s) < 11):
            print('NO')
            return
        elif(s.startswith('8') and len(s) == 11):
            print('YES')
            return
        elif(s.startswith('8')):
            s = s[:-1]
        else:
            s = s[1:]

t = int(input())
n = []
s = []
i = 0
for _ in range(t):
    n.insert(i,int(input()))
    s.insert(i,input())
    i+=1

for _ in range(t):
    createNumberPhone(n[_],s[_])


t = int(input())
for test in range(t):
    n = int(input())
    s = list(map(int,input()))
    if 8 in s:
        l = s.index(8)
        if (len(s)-l>=11):
            print('YES')
        else:
            print('NO')
    else:
        print('NO')


t = int(input())
for test in range(t):
    s = list(map(int,input()))
    l = s.index(8)
    if (len(s)-l>=11):
        print('YES')
    else:
        print('NO')


t = int(input())
for test in range(t):
    n = int(input())
    s = list(map(int,input()))
    l = s.index(8)
    if (len(s)-l>=11):
        print('YES')
    else:
        print('NO')


from sys import stdin, stdout
import sys
import math
INF=1e9
def get_int(): return int(stdin.readline().strip())
def get_ints(): return map(int,stdin.readline().strip().split())
def get_array(): return list(map(int,stdin.readline().strip().split()))
def get_string(): return stdin.readline().strip()
def op(c): return stdout.write(c)
#from collections import defaultdict
for _ in range(int(stdin.readline())):
    n=get_int()
    s=get_string()
    id=-1
    for i in range(n):
        if s[i]=='8':
            id=i
            break
    if id==-1:
        print("NO")
    elif id>n-11:
        print("NO")
    elif n==11 and id!=0:
        print('NO')
    else:
        print("YES")


from sys import stdin, stdout
import sys
import math
INF=1e9
def get_int(): return int(stdin.readline().strip())
def get_ints(): return map(int,stdin.readline().strip().split())
def get_array(): return list(map(int,stdin.readline().strip().split()))
def get_string(): return stdin.readline().strip()
def op(c): return stdout.write(c)
#from collections import defaultdict
for _ in range(int(stdin.readline())):
    n=get_int()
    s=get_string()
    if n<=11 :
        if s[0]!='8':
            print("NO")
            continue
        else:
            print("YES")
            continue
    else:
        for i in range(n-10):
            if s[i]=="8":
                print("YES")
                break
        else:
            print("NO")


from sys import stdin, stdout
import sys
import math
INF=1e9
def get_int(): return int(stdin.readline().strip())
def get_ints(): return map(int,stdin.readline().strip().split())
def get_array(): return list(map(int,stdin.readline().strip().split()))
def get_string(): return stdin.readline().strip()
def op(c): return stdout.write(c)
#from collections import defaultdict
for _ in range(int(stdin.readline())):
    n=get_int()
    s=get_string()
    if n<=11 and s[0]!='8':
        print("NO")
        continue
    else:
        for i in range(n-11):
            if s[i]=="8":
                print("YES")
                break
        else:
            print("NO")


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():
    return tuple(map(int,input().split()))
def array():
    return [int(i) for i in input().split()]

#-------------------------code---------------------------#
#vsInput()

for _ in range(int(input())):
    n=int(input())
    s=input()
    s+='8'
    i8=s.index('8')
    s=s[i8:]
    if(len(s)<11):
        print("NO")
    else:
        print("YES")


#------------------------template--------------------------#
import os
import sys
from math import *
from collections import *
from bisect import *
from io import BytesIO, IOBase
def vsInput():
    sys.stdin = open('input.txt', 'r')
    sys.stdout = open('output.txt', 'w')
BUFSIZE = 8192
class FastIO(IOBase):
    newlines = 0
    def __init__(self, file):
        self._fd = file.fileno()
        self.buffer = BytesIO()
        self.writable = "x" in file.mode or "r" not in file.mode
        self.write = self.buffer.write if self.writable else None
    def read(self):
        while True:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            if not b:
                break
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines = 0
        return self.buffer.read()
    def readline(self):
        while self.newlines == 0:
            b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
            self.newlines = b.count(b"\n") + (not b)
            ptr = self.buffer.tell()
            self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
        self.newlines -= 1
        return self.buffer.readline()
    def flush(self):
        if self.writable:
            os.write(self._fd, self.buffer.getvalue())
            self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
    def __init__(self, file):
        self.buffer = FastIO(file)
        self.flush = self.buffer.flush
        self.writable = self.buffer.writable
        self.write = lambda s: self.buffer.write(s.encode("ascii"))
        self.read = lambda: self.buffer.read().decode("ascii")
        self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def value():
    return tuple(map(int,input().split()))
def array():
    return [int(i) for i in input().split()]

#-------------------------code---------------------------#
#vsInput()

for _ in range(int(input())):
    n=int(input())
    s=input()
    try:
        i8=s.index('8')
    except:
        print("NO")
        continue
    s=s[i8:]
    if(len(s)<11):
        print("NO")
    else:
        print("YES")


n = int(input())
for i in range(n):
	k = int(input())
	s = input()
	a = 0
	for j in range(k - 10):
		if s[j] == '8':
			a = 1
			break
	if a:
		print('YES', end = '\n')
	else:
		print('NO', end = '\n')


n = int(input())
for i in range(n):
	k = int(input())
	s = input()
	a = 0
	if k < 8:
		continue
	for j in range(k - 7):
		if s[j] == '8':
			a = 1
			break
	if a:
		print('YES', end = '\n')
	else:
		print('NO', end = '\n')


def solve():
    n = int(input())
    s = input()
    try:
        return 'YES' if n >= (s.index('8') + 8) else 'No'
    except:
        return 'NO'

print('\n'.join(solve() for _ in range(int(input()))))


def solve():
    n = int(input())
    s = input()
    try:
        return 'YES' if n >= (s.index('8') + 11) else 'No'
    except:
        return 'NO'

print('\n'.join(solve() for _ in range(int(input()))))


#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <map>
#include <list>
#include <set>
#include <cstdio>
#include <cmath>
#include <iomanip>
#include <deque>
#include <ctime>
#include <cstring>

//#include <bits/stdc++.h>

using namespace std;

#define fr first
#define sd second
#define pb push_back
#define mp make_pair

#define endl '\n'

#define forr(i, n) for(ll (i) = 0LL; (i) < (n); (i)++)
#define mp3(a, b, c) mp(a, mp(b, c))

typedef long long ll;
typedef pair<ll, ll> pll;
typedef pair<ll, pll> plll;
typedef vector < vector < double > > vvd;
typedef vector < double > vd;
typedef vector < pair < double, double> > vdd;
typedef vector < vector < long long > > vvl;
typedef vector < long long > vl;
typedef vector < pll > vll;

int INT_MAX_VAL = (int) 1e20;
int INT_MIN_VAL = (int) -1e20;
ll LONG_MAX_VAL = (ll) 1e20;
ll LONG_MIN_VAL = (ll) -1e20;

#define MAXN 100005

#define MOD 1000000007

int main()
{
	ll t, a, b; cin >> t >> a >> b;

	if(t == 1) {
		if(a == 1) {
			if(a == b) {
				cout << "inf" << endl;
			} else {
				cout << 0 << endl;
			}
		} else {
			if(b % a == 0) {
				cout << 1 << endl;
			} else {
				cout << 0 << endl;
			}
		}
	} else {
		int ans = 0;
		if(a == b) ans++;
		ll ap = a, bi = b;
		ll tp = 1;
		ll tr = 0;
		while(bi > 0) {
			ll c = bi % a;
			bi /= a;
			tr += tp * c;
			tp *= t;
		}
		if(tr == a) {
			ans++;
		}
		cout << ans << endl;
	}

	return 0;
}


#include <bits/stdc++.h>

using namespace std;

vector<pair<long long, long long> > v[2];

int main(){
	long long t, a, b;
	cin >> t >> a >> b;
	if(t == a){
		if(a != b){
			cout << "0" << endl;
		}
		else if(t == 1){
			cout << "inf" << endl;
		}
		else{
			cout << "2" << endl;
		}
		return 0;
	}
	if((a-b)%abs(a-t)){
		cout << "0" << endl;
		return 0;
	}
	if(a < t){
		if(a == b){
			cout << "1" << endl;
		}
		else{
			cout << "0" << endl;
		}
		return 0;
	}
	bool read=0, write=1;
	long long tp=t, ap=a;
	v[write].push_back(make_pair(a, b));
	for(int i=32; i >= 2; --i){
		/*if(a/t < tp)
			break;
		if(b/a < ap)
			break;*/
		tp=1;
		ap=1;
		for(int j=0; j < i; ++j){
			if(a/t < tp)
				tp=a+1;
			else
				tp=tp*t;
			if(b/t < ap)
				ap=b+1;
			else
				ap=ap*a;
		}
		write^=1;
		read^=1;
		v[write].clear();
		tp*=t;
		ap*=a;
		for(int j=0; j < v[read].size(); ++j){
			long long A=v[read][j].first;
			long long B=v[read][j].second;
			for(int k=0; tp*k <= A && ap*k <= B; ++k){
				long long nA=A-tp*k;
				long long nB=B-ap*k;
				if(A/tp < B/ap)
					continue;
				v[write].push_back(make_pair(A-tp*k, B-ap*k));
			}
		}
	}
	long long ans=0;
	for(int i=0; i < v[write].size(); ++i){
		long long A=v[write][i].first;
		long long B=v[write][i].second;
		if((A-B)%(t-a))
			continue;
		long long c1=(A-B)/(t-a);
		long long c0=A-c1*t;
		if(c1 >= 0 && c0 >= 0)++ans;
	}
	cout << ans << endl;
}


#include <bits/stdc++.h>

using namespace std;

vector<pair<long long, long long> > v[2];

int main(){
	long long t, a, b;
	cin >> t >> a >> b;
	if(t == a){
		if(a != b){
			cout << "0" << endl;
		}
		else if(t == 1){
			cout << "inf" << endl;
		}
		else{
			cout << "2" << endl;
		}
		return 0;
	}
	if(a < t){
		if(a == b){
			cout << "1" << endl;
		}
		else{
			cout << "0" << endl;
		}
		return 0;
	}
	if((a-b)%(t-a)){
		cout << "0" << endl;
		return 0;
	}
	bool read=0, write=1;
	long long tp=t, ap=a;
	v[write].push_back(make_pair(a, b));
	for(int i=32; i >= 2; --i){
		/*if(a/t < tp)
			break;
		if(b/a < ap)
			break;*/
		tp=1;
		ap=1;
		for(int j=0; j < i; ++j){
			if(a/t < tp)
				tp=a+1;
			else
				tp=tp*t;
			if(b/a < ap)
				ap=b+1;
			else
				ap=ap*a;
		}
		write^=1;
		read^=1;
		v[write].clear();
		for(int j=0; j < v[read].size(); ++j){
			long long A=v[read][j].first;
			long long B=v[read][j].second;
			for(int k=0; tp*k <= A && ap*k <= B; ++k){
				long long nA=A-tp*k;
				long long nB=B-ap*k;
				if(tp <= a && ap <= b && tp >= t && ap >= a && nA/(tp/t) < nB/(ap/a))
					continue;
				v[write].push_back(make_pair(A-tp*k, B-ap*k));
			}
		}
	}
	long long ans=0;
	for(int i=0; i < v[write].size(); ++i){
		long long A=v[write][i].first;
		long long B=v[write][i].second;
		if((A-B)%(t-a))
			continue;
		long long c1=(A-B)/(t-a);
		long long c0=A-c1*t;
		if(c1 >= 0 && c0 >= 0)++ans;
	}
	cout << ans << endl;
}