#include <iostream>
#include <algorithm>
#include <map>
#include <vector>
#include <cmath>

using namespace std;

int main()
{
    int n,m,a[200005],b[200005],k=0,m1=0;
    map <long long,long long> x;
    long long sum=0;
    cin>>n>>m;
    for (int i=0;i<n;i++)
        cin>>a[i];
    for (int i=1;i<=m;i++)
    {
        cin>>b[i];
        if (b[i]==0) m1++;
        sum+=b[i];
    }
    m-=m1;
    long long ans=0,ans1=1e18,startpos=0;
    for (int i=0;i<n;i++)
    {
        x[a[i]]++;
        ans++;
        if (x[a[i]]==b[a[i]]) k++;
        if (k>=m)
        {
            while (x[a[startpos]]>b[a[startpos]])
            {
                x[a[startpos]]--;
                ans--;
                startpos++;
            }
            ans1=min(ans1,ans);
        }
    }
    if (ans1==1e18) cout<<-1;
    else cout<<ans1-sum;
    return 0;
}


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <bits/stdc++.h>
// #define int long long
#define mod 1000000007
using namespace std;
const int N = 1e5 +100;

int a[N];
int d[N];
int h[N];
int32_t main()
{

	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif
	int n;
	cin >> n;
	int k;
	cin >> k
	;
	for(int i=0;i<n;i++)
		cin >> a[i];
	for(int i=1;i<=k;i++)
		cin >> h[i];
	int l = 0;
	int r = 0;
	int hvd = 0;
	int ex = 0;
	int ans = mod;
	while(r < n)
	{
		while(hvd < k && r < n)
		{
			d[a[r]]++;
			if( d[a[r]] == h[a[r]] )
			{
				hvd ++ ;
			}
			if( d[a[r]] > h[a[r]] )
			{
				ex ++ ;
			}
			// cout <<r << " "<< a[r]<<" " << h[a[r]]<<" "<< d[a[r]] <<" " << hvd << endl;
			r++;
		}
		// cout << r << endl;
		if(hvd >= k)
			ans = min(ans, ex);
		while(hvd >= k && l < r)
		{
			d[a[l]]--;
			if( d[a[l]] == h[a[l]]-1 )
			{
				hvd -- ;
			}
			if( d[a[l]] >= h[a[l]] )
			{
				ex -- ;
			}
			// cout <<l << " "<< a[l]<<" " << h[a[l]]<<" "<< d[a[l]] << " " << ex << " " << hvd << endl;
			if(hvd >= k)
				ans = min(ans, ex);
			l++;
		}
	}
	if(ans == mod)
		cout << - 1 ; else cout << ans ;
	return 0;

}


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <bits/stdc++.h>
// #define int long long
#define mod 1000000007
using namespace std;
const int N = 2e5 +100;

int a[N];
int d[N];
int h[N];
int32_t main()
{

	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif
	int n;
	cin >> n;
	int k;
	cin >> k
	;
	for(int i=0;i<n;i++)
		cin >> a[i];
	for(int i=1;i<=k;i++)
		cin >> h[i];
	int l = 0;
	int r = 0;
	int hvd = 0;
	int ex = 0;
	int ans = mod;
	while(r <= n)
	{
		while(hvd < k && r < n)
		{
			d[a[r]]++;
			if( d[a[r]] == h[a[r]] )
			{
				hvd ++ ;
			}
			if( d[a[r]] > h[a[r]] )
			{
				ex ++ ;
			}
			// cout <<r << " "<< a[r]<<" " << h[a[r]]<<" "<< d[a[r]] <<" " << hvd << endl;
			r++;
		}
		// cout << r << endl;
		if(hvd >= k)
			ans = min(ans, ex);
		while(hvd >= k && l < r)
		{
			d[a[l]]--;
			if( d[a[l]] == h[a[l]]-1 )
			{
				hvd -- ;
			}
			if( d[a[l]] >= h[a[l]] )
			{
				ex -- ;
			}
			// cout <<l << " "<< a[l]<<" " << h[a[l]]<<" "<< d[a[l]] << " " << ex << " " << hvd << endl;
			if(hvd >= k)
				ans = min(ans, ex);
			l++;
		}
	}
	if(ans == mod)
		cout << - 1 ; else cout << ans ;
	return 0;

}


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <bits/stdc++.h>
// #define int long long
#define mod 1000000007
using namespace std;
const int N = 2e5 +100;

int a[N];
int d[N];
int h[N];
int32_t main()
{

	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif
	int n;
	cin >> n;
	int k;
	cin >> k
	;
	for(int i=0;i<n;i++)
		cin >> a[i];
	for(int i=1;i<=k;i++)
		cin >> h[i];
	int l = 0;
	int r = 0;
	int hvd = 0;
	int ex = 0;
	int ans = mod;
	while(r < n)
	{
		while(hvd < k && r < n)
		{
			d[a[r]]++;
			if( d[a[r]] == h[a[r]] )
			{
				hvd ++ ;
			}
			if( d[a[r]] > h[a[r]] )
			{
				ex ++ ;
			}
			// cout <<r << " "<< a[r]<<" " << h[a[r]]<<" "<< d[a[r]] <<" " << hvd << endl;
			r++;
		}
		// cout << r << endl;
		if(hvd >= k)
			ans = min(ans, ex);
		while(hvd >= k && l < r)
		{
			d[a[l]]--;
			if( d[a[l]] == h[a[l]]-1 )
			{
				hvd -- ;
			}
			if( d[a[l]] >= h[a[l]] )
			{
				ex -- ;
			}
			// cout <<l << " "<< a[l]<<" " << h[a[l]]<<" "<< d[a[l]] << " " << ex << " " << hvd << endl;
			if(hvd >= k)
				ans = min(ans, ex);
			l++;
		}
	}
	if(ans == mod)
		cout << - 1 ; else cout << ans ;
	return 0;

}


#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <bits/stdc++.h>
// #define int long long
#define mod 1000000007
using namespace std;
const int N = 2e5 +100;

int a[N];
int d[N];
int h[N];
int32_t main()
{

	#ifndef ONLINE_JUDGE
	freopen("input.txt","r",stdin);
	freopen("output.txt","w",stdout);
	#endif
	int n;
	cin >> n;
	int k;
	cin >> k
	;
	int hvd = 0;
	for(int i=0;i<n;i++)
		cin >> a[i];
	for(int i=1;i<=k;i++){
		cin >> h[i];
		if(h[i] == 0)
			hvd ++;
	}
	int l = 0;
	int r = 0;
	int ex = 0;
	int ans = mod;
	while(r < n)
	{
		while(hvd < k && r < n)
		{
			d[a[r]]++;
			if( d[a[r]] == h[a[r]] )
			{
				hvd ++ ;
			}
			if( d[a[r]] > h[a[r]] )
			{
				ex ++ ;
			}
			// cout <<r << " "<< a[r]<<" " << h[a[r]]<<" "<< d[a[r]] <<" " << hvd << endl;
			r++;
		}
		// cout << r << endl;
		if(hvd == k)
			ans = min(ans, ex);
		while(hvd == k && l < r)
		{
			d[a[l]]--;
			if( d[a[l]] == h[a[l]]-1 )
			{
				hvd -- ;
			}
			if( d[a[l]] >= h[a[l]] )
			{
				ex -- ;
			}
			// cout <<l << " "<< a[l]<<" " << h[a[l]]<<" "<< d[a[l]] << " " << ex << " " << hvd << endl;
			if(hvd >= k)
				ans = min(ans, ex);
			l++;
		}
	}
	if(ans == mod)
		cout << - 1 ; else cout << ans ;
	return 0;

}


#include<bits/stdc++.h>

using namespace std;

typedef long long int ll;

int a[200],b[200];
multiset<int> s;

int main()
{
	int n,m,tot = 0, ts = 0;scanf("%d%d", &n, &m);
	for(int i = 1; i<=n; ++i){
		cin>>a[i];tot += a[i];
	}
	for(int i = 1; i<=m; ++i){
		cin>>b[i], ts += b[i];
		s.insert(b[i]);
	}
	int mx = *--s.end(), ans = 1e9;
	for(int i = 1, j = 1; i<=n; ++i)
	{
		s.erase(s.find(b[a[i]]));
		--b[a[i]];
		s.insert(b[a[i]]);
		mx = *--s.end();
	//	cerr << j << ' ' << i << endl;
		//for(int i = 1; i<=m; ++i)cerr << b[i] << ' ';
		//cerr << endl;
		while(mx<=0){
			ans = min(ans, i-j+1 - ts);
			s.erase(s.find(b[a[j]]));
			b[a[j]]++;
			s.insert(b[a[j]]);
			mx = *--s.end();
			++j;
		}
	}
	cout << ans << endl;

   return 0;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long int ll;

int a[200],b[200];
multiset<int> s;

int main()
{
	int n,m,tot = 0, ts = 0;scanf("%d%d", &n, &m);
	for(int i = 1; i<=n; ++i){
		cin>>a[i];tot += a[i];
	}
	for(int i = 1; i<=m; ++i){
		cin>>b[i], ts += b[i];
		s.insert(b[i]);
	}
	int mx = *--s.end(), ans = 1e9;
	for(int i = 1, j = 1; i<=n; ++i)
	{
		s.erase(s.find(b[a[i]]));
		--b[a[i]];
		s.insert(b[a[i]]);
		mx = *--s.end();
	//	cerr << j << ' ' << i << endl;
		//for(int i = 1; i<=m; ++i)cerr << b[i] << ' ';
		//cerr << endl;
		while(mx<=0){
			ans = min(ans, i-j+1 - ts);
			s.erase(s.find(b[a[j]]));
			b[a[j]]++;
			s.insert(b[a[j]]);
			mx = *--s.end();
			++j;
		}
	}
	if(ans<1e9)cout << ans << endl;
	else cout << -1 << endl;

   return 0;
}


#include<bits/stdc++.h>

using namespace std;

typedef long long int ll;

int a[200007],b[200007];
multiset<int> s;

int main()
{
	int n,m,tot = 0, ts = 0;scanf("%d%d", &n, &m);
	for(int i = 1; i<=n; ++i){
		scanf("%d", &a[i]);tot += a[i];
	}
	for(int i = 1; i<=m; ++i){
		scanf("%d", &b[i]);ts += b[i];
		s.insert(b[i]);
	}
	int mx = *--s.end(), ans = 1e9;
	for(int i = 1, j = 1; i<=n; ++i)
	{
		s.erase(s.find(b[a[i]]));
		--b[a[i]];
		s.insert(b[a[i]]);
		mx = *--s.end();
	//	cerr << j << ' ' << i << endl;
		//for(int i = 1; i<=m; ++i)cerr << b[i] << ' ';
		//cerr << endl;
		while(mx<=0){
			ans = min(ans, i-j+1 - ts);
			s.erase(s.find(b[a[j]]));
			b[a[j]]++;
			s.insert(b[a[j]]);
			mx = *--s.end();
			++j;
		}
	}
	if(ans<1e9)printf("%d\n", ans);
	else printf("-1\n");

   return 0;
}


#include <bits/stdc++.h>
#define sz(a) (int) a.size()

using namespace std;

using ll = long long;
using pii = pair<int,int>;
using vi = vector<int>;

const int INF = 1e9 + 1000;
const int MAX = 2e5;

int N, M;
int arr[MAX+5], cnt[MAX+5];
multiset<int> ms;

bool check() {
	return ms.empty() ? false : *ms.begin() >= 0;
}

int get() {
	int ret = 0;
	for (int x : ms) ret += x;
	return ret;
}

void update(int x, int val) {
	auto it = ms.find(cnt[x]);
	ms.erase(it);

	cnt[x] += val;
	ms.insert(cnt[x]);
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> N >> M;
	for (int i=0; i<N; i++) cin >> arr[i];
	for (int i=1; i<=M; i++) {
		cin >> cnt[i];
		cnt[i] = -cnt[i];
		ms.insert(cnt[i]);
	}

	int ans = INF;
	int i = 0, j = 0;

	while (i < N) {
		// cout << "masuk\n";
		while (j < N && !check()) {
			update(arr[j], 1);
			j++;

			// cout << i << " " << j << " : " << ans << " -- " << get() << "\n";
			if (check()) {
				ans = min(ans, get());
				break;
			}
		}
		// cout << "keluar\n";

		update(arr[i], -1);
		i++;

		// cout << i << " " << j << " : " << ans << " -- " << get() << "\n";
		if (check()) ans = min(ans, get());
	}

	cout << (ans == INF ? -1 : ans)	 << "\n";
	return 0;
}


#include <bits/stdc++.h>
#define sz(a) (int) a.size()

using namespace std;

using ll = long long;
using pii = pair<int,int>;
using vi = vector<int>;

const int INF = 1e9 + 1000;
const int MAX = 2e5;

int N, M;
int arr[MAX+5], k[MAX+5], cnt[MAX+5];

int check() {
	// for (int i=1; i<=M; i++) cout << cnt[i] << " "; cout << "\n";
	int diff = 0;
	for (int i=1; i<=M; i++) {
		if (cnt[i] < 0) throw -1;
		if (cnt[i] >= k[i]) diff += cnt[i] - k[i];
		else return -1;
	}

	return diff;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> N >> M;
	for (int i=0; i<N; i++) cin >> arr[i];
	for (int i=1; i<=M; i++) cin >> k[i];

	int ans = INF;
	int i = 0, j = 0;

	while (i < N) {
		// cout << "masuk\n";
		while (j < N && check() == -1) {
			cnt[arr[j]]++;
			j++;

			int tmp = check();
			// cout << i << " " << j << " : " << ans << " -- " << tmp << "\n";
			if (tmp >= 0) {
				ans = min(ans, tmp);
				break;
			}
		}
		// cout << "keluar\n";

		cnt[arr[i]]--;
		i++;

		int tmp = check();
		// cout << i << " " << j << " : " << ans << " -- " << tmp << "\n";
		if (tmp >= 0) ans = min(ans, tmp);
	}

	cout << (ans == INF ? -1 : ans)	 << "\n";
	return 0;
}


#include <bits/stdc++.h>
#define sz(a) (int) a.size()

using namespace std;

using ll = long long;
using pii = pair<int,int>;
using vi = vector<int>;

const int INF = 1e9 + 1000;
const int MAX = 2e5;

int N, M;
int arr[MAX+5], cnt[MAX+5];
multiset<int> ms;
int sum;

bool check() {
	return ms.empty() ? false : *ms.begin() >= 0;
}

void update(int x, int val) {
	auto it = ms.find(cnt[x]);
	ms.erase(it);

	cnt[x] += val;
	ms.insert(cnt[x]);

	sum += val;
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);

	cin >> N >> M;
	for (int i=0; i<N; i++) cin >> arr[i];
	for (int i=1; i<=M; i++) {
		cin >> cnt[i];
		cnt[i] = -cnt[i];

		ms.insert(cnt[i]);
		sum += cnt[i];
	}

	// cout << sum << "\n";

	int ans = INF;
	int i = 0, j = 0;

	while (i < N) {
		// cout << "masuk\n";
		while (j < N && !check()) {
			update(arr[j], 1);
			j++;

			// cout << i << " " << j << " : " << ans << " -- " << get() << "\n";
			if (check()) {
				ans = min(ans, sum);
				break;
			}
		}
		// cout << "keluar\n";

		update(arr[i], -1);
		i++;

		// cout << i << " " << j << " : " << ans << " -- " << get() << "\n";
		if (check()) ans = min(ans, sum);
	}

	cout << (ans == INF ? -1 : ans)	 << "\n";
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ll long long

int n,m;

int a[200010];
int b[200010];
int c[200010];

int main(){
    cin>>n>>m;
    set<int> s;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    int sum = 0;
    for(int i=1;i<=m;i++){
        scanf("%d",&b[i]);
        sum += b[i];
        s.insert(i);
    }

    bool ok = 0;
    int ans = 1e9;
    int l = 0;
    for(int r=1;r<=n;r++){
        int color = a[r];
        c[color]++;
        if(c[color] >= b[color]){
            s.erase(color);
        }

        if(s.size() == 0){
            ok = 1;
            ans = min(ans,r-l-sum);
        }
        while(l<r && s.size() == 0){
            l++;
            c[a[l]]--;
            if(c[a[l]] < b[a[l]]){
                s.insert(a[l]);
            }
            if(s.size() == 0){
                ok = 1;
                ans = min(ans,r-l-sum);
            }
        }

    }

    if(ok){
        cout<<ans<<endl;
    }else{
        cout<<-1<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ll long long

int n,m;

int a[200010];
int b[200010];
int c[200010];

int main(){
    cin>>n>>m;
    set<int> s;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    int sum = 0;
    for(int i=1;i<=m;i++){
        scanf("%d",&b[i]);
        sum += b[i];
        s.insert(i);
    }

    bool ok = 0;
    int ans = 1e9;
    int l = 0;
    for(int r=1;r<=n;r++){
        int color = a[r];
        c[color]++;
        if(c[color] >= b[color]){
            s.erase(color);
        }

        if(s.size() == 0){
            ok = 1;
            ans = min(ans,r-l-sum);
        }
        while( (l<r) && (s.size() == 0) ){
            ans = min(ans,r-l-sum);

            l++;
            c[a[l]]--;
            if(c[a[l]] < b[a[l]]){
                s.insert(a[l]);
            }
        }

    }

    if(ok){
        cout<<ans<<endl;
    }else{
        cout<<-1<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ll long long

int n,m;

int a[200010];
int b[200010];
int c[200010];

int main(){
    cin>>n>>m;
    set<int> s;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    int sum = 0;
    for(int i=1;i<=m;i++){
        scanf("%d",&b[i]);
        sum += b[i];
        s.insert(i);
    }

    bool ok = 0;
    int ans = 1e9;
    int l = 0;
    for(int r=1;r<=n;r++){
        int color = a[r];
        c[color]++;
        if(c[color] == b[color]){
            s.erase(color);
        }
        if(s.size() == 0){
            ok = 1;
            ans = min(ans,r-l-sum);
        }

        while(l<=r && s.size() == 0){
            l++;
            c[a[l]]--;
            if(c[a[l]] < b[a[l]]){
                s.insert(a[l]);
            }
        }
    }

    if(ok){
        cout<<ans<<endl;
    }else{
        cout<<-1<<endl;
    }
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

#define ll long long

int n,m;

int a[200010];
int b[200010];
int c[200010];

int main(){
    cin>>n>>m;
    set<int> s;
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    int sum = 0;
    for(int i=1;i<=m;i++){
        scanf("%d",&b[i]);
        sum += b[i];
        if(b[i])s.insert(i);
    }

    bool ok = 0;
    int ans = 1e9;
    int l = 0;
    for(int r=1;r<=n;r++){
        int color = a[r];
        c[color]++;
        if(c[color] >= b[color]){
            s.erase(color);
        }

        if(s.size() == 0){
            ok = 1;
            ans = min(ans,r-l-sum);
        }
        while( (l<r) && (s.size() == 0) ){
            ans = min(ans,r-l-sum);

            l++;
            c[a[l]]--;
            if(c[a[l]] < b[a[l]]){
                s.insert(a[l]);
            }
        }

    }

    if(ok){
        cout<<ans<<endl;
    }else{
        cout<<-1<<endl;
    }
    return 0;
}


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int N = 200005;
inline int read() {
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9') {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9') {
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*f;
}
int ans = 1e9;
int n,m,col[N],k[N],res,t[N],sum;
void print() {
	cout<<endl;
	for(int i = 1;i<=m;i++) cout<<t[i]<<" ";
	cout<<sum<<endl;
}
int main () {
	n = read();m = read();
	for(int i = 1;i<=n;i++) col[i] = read();
	for(int i = 1;i<=m;i++) {
		k[i] = read();
		res += k[i];
		sum += (!k[i]);
	}
	int l = 1;
	for(int r = 1;r<=n;r++) {
		++t[col[r]];
		if(t[col[r]] == k[col[r]]) ++sum;
		if(sum == m) {
			while(l<=r&&t[col[l]]>k[col[l]]) t[col[l++]]--;
//			cout<<l<<" "<<r<<endl;
		    ans = min(ans,r-l+1-res);
		}
//		print();
	}
	if(ans == 1e9) ans = -1;
	printf("%d\n",ans);
}


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int N = 200005;
inline int read() {
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9') {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9') {
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*f;
}
int ans = 1e9;
int n,m,col[N],k[N],res,t[N],sum;
void print() {
	cout<<endl;
	for(int i = 1;i<=m;i++) cout<<t[i]<<" ";
	cout<<sum<<endl;
}
int main () {
	n = read();m = read();
	for(int i = 1;i<=n;i++) col[i] = read();
	for(int i = 1;i<=m;i++) k[i] = read(),res += k[i];
	int l = 1;
	for(int r = 1;r<=n;r++) {
		++t[col[r]];
		if(t[col[r]] == k[col[r]]) ++sum;
		if(sum == m) {
			while(l<=r&&t[col[l]]>k[col[l]]) t[col[l++]]--;
//			cout<<l<<" "<<r<<endl;
		    ans = min(ans,r-l+1-res);
		}
//		print();
	}
	if(ans == 1e9) ans = -1;
	printf("%d\n",ans);
}


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int N = 200005;
inline int read() {
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9') {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9') {
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*f;
}
int ans = 1e9;
int n,m,col[N],k[N],res,t[N],sum;
void print() {
	cout<<endl;
	for(int i = 1;i<=m;i++) cout<<t[i]<<" ";
	cout<<sum<<endl;
}
int main () {
	n = read();m = read();
	for(int i = 1;i<=n;i++) col[i] = read();
	for(int i = 1;i<=m;i++) {
		k[i] = read();
		if(k[i]) res += k[i];
	}
	int l = 1;
	for(int r = 1;r<=n;r++) {
		++t[col[r]];
		if(t[col[r]] == k[col[r]]) ++sum;
		if(sum == m) {
			while(l<=r&&t[col[l]]>k[col[l]]) t[col[l++]]--;
//			cout<<l<<" "<<r<<endl;
		    ans = min(ans,r-l+1-res);
		}
//		print();
	}
	if(ans == 1e9) ans = -1;
	printf("%d\n",ans);
}


#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;
const int N = 200005;
inline int read() {
    int x=0,f=1;
    char ch=getchar();
    while(ch<'0'||ch>'9') {
        if(ch=='-')
            f=-1;
        ch=getchar();
    }
    while(ch>='0'&&ch<='9') {
        x=(x<<1)+(x<<3)+(ch^48);
        ch=getchar();
    }
    return x*f;
}
int ans = 1e9;
int n,m,col[N],k[N],res,t[N],sum;
void print() {
	cout<<endl;
	for(int i = 1;i<=m;i++) cout<<t[i]<<" ";
	cout<<sum<<endl;
}
int main () {
	n = read();m = read();
	for(int i = 1;i<=n;i++) col[i] = read();
	for(int i = 1;i<=m;i++) k[i] = read(),res += k[i];
	int l = 1;
	for(int r = 1;r<=n;r++) {
		++t[col[r]];
		if(t[col[r]] == k[col[r]]) ++sum;
		if(sum == m) {
			while(l<=r&&t[col[l]]>k[col[l]]) t[col[l++]]--;
//			cout<<l<<" "<<r<<endl;
		    ans = min(ans,r-l+1-res);
		}
		print();
	}
	if(ans == 1e9) ans = -1;
	printf("%d\n",ans);
}


#include<bits/stdc++.h>
using namespace std;
#define fu(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,n) fu(i,1,n)
#define re(i,n) fu(i,0,n - 1)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define M 1000000007
#define pii pair< int,int >
#define pll pair< ll,ll >
#define sz(a) a.size()
#define all(a) a.begin(),a.end()
#define inf (1000*1000*1000+5)
const int LG = 30;
const int N = 200005;
int gcd(int a,int b) {

    if(a==0) return b;
    else return gcd(b%a,a);
}
typedef vector< vector<char> > matrix1;
typedef vector< vector<ll> > matrix;
int a[N];
int b[N];
int cnt[N];
int main() {

    	ios_base::sync_with_stdio(false);
    	cin.tie(NULL);
    	cout.tie(NULL);
    	matrix1 A(12,vector<char>(12));
    	matrix1 B(12,vector<char>(12));
    	int n,m;
    	cin  >> n >> m;
    	int sum = 0;
    	fu(i,1,n) {
				cin >> a[i];
			}
		fu(i,1,m) {
				cin >> b[i];
				sum += b[i];
			}
		int ans = N;
		int i = 1, j = 1;
		int req = m;
		int f = 0;
		for (int i = 1; i <= m; i++)
			if (b[i] == 0) req--;
		while (j <= n + 1) {

				if (req == 0) {
						cnt[a[i]]--;
						if (cnt[a[i]] < b[a[i]]) req++;
						i++;
					}
				else {
						cnt[a[j]]++;
						if (cnt[a[j]] == b[a[j]]) {
								req--;
							}
						j++;
					}
				if (j >= n + 1 && req > 0) break;
				if (req == 0) {
					f = 1;
					ans = min(ans,(j - i) - sum);
					}
			}
		if (!f) {
				cout << -1 << endl;
				return 0;
			}
		cout << ans << endl;
		return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define fu(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,n) fu(i,1,n)
#define re(i,n) fu(i,0,n - 1)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define M 1000000007
#define pii pair< int,int >
#define pll pair< ll,ll >
#define sz(a) a.size()
#define all(a) a.begin(),a.end()
#define inf (1000*1000*1000+5)
const int LG = 30;
const int N = 200005;
int gcd(int a,int b) {

    if(a==0) return b;
    else return gcd(b%a,a);
}
typedef vector< vector<char> > matrix1;
typedef vector< vector<ll> > matrix;
int a[N];
int b[N];
int cnt[N];
int main() {

    	ios_base::sync_with_stdio(false);
    	cin.tie(NULL);
    	cout.tie(NULL);
    	matrix1 A(12,vector<char>(12));
    	matrix1 B(12,vector<char>(12));
    	int n,m;
    	cin  >> n >> m;
    	int sum = 0;
    	fu(i,1,n) {
				cin >> a[i];
			}
		fu(i,1,m) {
				cin >> b[i];
				sum += b[i];
			}
		int ans = N;
		int i = 1, j = 1;
		int req = m;
		int f = 0;
		while (j <= n) {
				if (req == 0) {
						cnt[a[i]]--;
						if (cnt[a[i]] < b[a[i]]) req++;
						i++;
					}
				else {
						cnt[a[j]]++;
						if (cnt[a[j]] == b[a[j]]) {
								req--;
							}
						j++;
					}

				if (req == 0) {
					f = 1;
					ans = min(ans,(j - i) - sum);
					}
			}
		if (!f) {
				cout << -1 << endl;
				return 0;
			}
		cout << ans << endl;
		return 0;
}


#include<bits/stdc++.h>
using namespace std;
#define fu(i,a,b) for(int i=a;i<=b;i++)
#define rep(i,n) fu(i,1,n)
#define re(i,n) fu(i,0,n - 1)
#define fd(i,a,b) for(int i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define M 1000000007
#define pii pair< int,int >
#define pll pair< ll,ll >
#define sz(a) a.size()
#define all(a) a.begin(),a.end()
#define inf (1000*1000*1000+5)
const int LG = 30;
const int N = 200005;
int gcd(int a,int b) {

    if(a==0) return b;
    else return gcd(b%a,a);
}
typedef vector< vector<char> > matrix1;
typedef vector< vector<ll> > matrix;
int a[N];
int b[N];
int cnt[N];
int main() {

    	ios_base::sync_with_stdio(false);
    	cin.tie(NULL);
    	cout.tie(NULL);
    	matrix1 A(12,vector<char>(12));
    	matrix1 B(12,vector<char>(12));
    	int n,m;
    	cin  >> n >> m;
    	int sum = 0;
    	fu(i,1,n) {
				cin >> a[i];
			}
		fu(i,1,m) {
				cin >> b[i];
				sum += b[i];
			}
		int ans = N;
		int i = 1, j = 1;
		int req = m;
		int f = 0;
		for (int i = 1; i <= m; i++)
			if (b[i] == 0) req--;
		while (j <= n) {
				if (req == 0) {
						cnt[a[i]]--;
						if (cnt[a[i]] < b[a[i]]) req++;
						i++;
					}
				else {
						cnt[a[j]]++;
						if (cnt[a[j]] == b[a[j]]) {
								req--;
							}
						j++;
					}

				if (req == 0) {
					f = 1;
					ans = min(ans,(j - i) - sum);
					}
			}
		if (!f) {
				cout << -1 << endl;
				return 0;
			}
		cout << ans << endl;
		return 0;
}


//K.Chaitanya
#include <bits/stdc++.h>
using namespace std;
#define f(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) f(i,0,n)
#define fd(i,a,b) for(i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define pii pair< int,int >
#define pll pair< ll,ll >
#define sz(a) a.size()
#define inf (1000*1000*1000+5)
#define all(a) a.begin(),a.end()
#define tri pair<int,pii>
#define vii vector<pii>
#define vll vector<pll>
#define viii vector<tri>
#define mod (1000*1000*1000+7)
#define pqueue priority_queue< int >
#define pdqueue priority_queue< int,vi ,greater< int > >
//std::ios::sync_with_stdio(false);
const int N = 212345;
ll v[N][100];
ll a[N],b[100];
vector< vector< int > > g(N);
int main(){
    std::ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
	ll n,m,sum=0;
	cin>>n>>m;
	for(ll i=1;i<=n;i++) {
			cin>>a[i];
			g[a[i]].pb(i);
	}
	for(ll i=1;i<=m;i++) {
		cin>>b[i];
		sum+=b[i];
	}
	ll mini=N;
	for(ll i=1;i<=n;i++){
		ll lo=i+sum-1,hi=n,mid;
		ll c;
		int f;
		while(lo<hi){
			mid=lo+(hi-lo)/2;
			f=0;
			for(ll j=1;j<=m;j++){

				vector<int>::iterator itu = lower_bound(all(g[j]),mid + 1);
				vector<int>::iterator itl = lower_bound(all(g[j]),i);
				int dist = distance(itl,itu);
				if(dist<b[j]){
					f=1;
					break;
				}
			}
			if(f==0){
				hi=mid;
			}
			else lo=mid+1;
		}
		 c=0;
	    f=0;
		for(ll j=1;j<=m;j++){
				vector<int>::iterator itu = lower_bound(all(g[j]),lo + 1);
				vector<int>::iterator itl = lower_bound(all(g[j]),i);
				int dist = distance(itl,itu);
				if(dist<b[j]){
					f=1;
					break;
				}
				else{
					c+=(dist)-b[j];
				}
		}
		if(f==0){
			mini=min(mini,c);
		}
	}
	if(mini==N) cout<<-1<<endl;
	else cout<<mini<<endl;
	return 0;
}


#include<bits/stdc++.h>
#define maxn 200007
#define ll long long int
using namespace std;

int a[maxn],x[maxn],cnt[maxn]={0};
int n,m,tot=0,flag=1,fh=0,l=1,ans=0;

inline ll read()
{
	ll x=0,f=1;
	char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*f;
}

inline void writ(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) writ(x/10);
	putchar(x%10+'0');
}
inline void write(int x){writ(x);putchar(' ');}

int main()
{
	n=read(),m=read();
	for (int i=1;i<=n;++i) a[i]=read();
	for (int i=1;i<=m;++i) {x[i]=read();if (x[i]==0) ++tot;}
	for (int i=1;i<=n;++i)
	{
		++cnt[a[i]];
		if (cnt[a[i]]==x[a[i]]) ++tot;
		if (tot==m) {flag=0;break;}
		fh=i;
	}
	if (flag){write(-1);return 0;}
	for (int i=1;i<=m;++i) ans+=cnt[i]-x[i];
	int mx=ans;
	for (int i=fh+1;i<=n;++i)
	{
		while (cnt[a[l]]>x[a[l]]) --mx,--cnt[a[l]],++l;
		if (mx<ans) ans=mx;
		++cnt[a[i]],++mx;
	}
	write(ans);
	return 0;
}


#include<bits/stdc++.h>
#define maxn 200007
#define ll long long int
using namespace std;

int a[maxn],x[maxn],cnt[maxn]={0};
int n,m,tot=0,flag=1,fh=0,l=1,ans=0;

inline ll read()
{
	ll x=0,f=1;
	char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*f;
}

inline void writ(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) writ(x/10);
	putchar(x%10+'0');
}
inline void write(int x){writ(x);putchar(' ');}

int main()
{
	n=read(),m=read();
	for (int i=1;i<=n;++i) a[i]=read();
	for (int i=1;i<=m;++i) {x[i]=read();if (x[i]==0) ++tot;}
	for (int i=1;i<=n;++i)
	{
		++cnt[a[i]];
		if (cnt[a[i]]==x[a[i]]) ++tot;
		if (tot==m) {flag=0;break;}
		fh=i;
	}
	if (flag){write(-1);return 0;}
	for (int i=1;i<=m;++i) ans+=cnt[i]-x[i];
	int mx=ans;
	for (int i=fh+1;i<=n;++i)
	{
		while (cnt[a[l]]>x[a[l]]) --mx,--cnt[a[l]],++l;
		if (mx<ans) ans=mx;
		++cnt[a[i]],++mx;
	}
	while (cnt[a[l]]>x[a[l]]) --mx,--cnt[a[l]],++l;
	if (mx<ans) ans=mx;
	write(ans);
	return 0;
}


#include<bits/stdc++.h>
#define maxn 200007
#define ll long long int
using namespace std;

int a[maxn],x[maxn],cnt[maxn]={0};
int n,m,tot=0,flag=1,fh=0,l=1,ans=0;

inline ll read()
{
	ll x=0,f=1;
	char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*f;
}

inline void writ(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) writ(x/10);
	putchar(x%10+'0');
}
inline void write(int x){writ(x);putchar(' ');}

int main()
{
	n=read(),m=read();
	for (int i=1;i<=n;++i) a[i]=read();
	for (int i=1;i<=m;++i) {x[i]=read();if (x[i]==0) ++tot;}
	for (int i=1;;++i)
	{
		++cnt[a[i]];
		if (cnt[a[i]]==x[a[i]]) ++tot;
		if (tot==m) {flag=0;break;}
		fh=i;
	}
	if (flag){write(-1);return 0;}
	for (int i=1;i<=m;++i) ans+=cnt[i]-x[i];
	int mx=ans;
	for (int i=fh+1;i<=n;++i)
	{
		while (cnt[a[l]]>x[a[l]]) --mx,--cnt[a[l]],++l;
		if (mx<ans) ans=mx;
		++cnt[a[i]],++mx;
	}
	write(ans);
	return 0;
}


#include<bits/stdc++.h>
#define maxn 200007
#define ll long long int
using namespace std;

int a[maxn],x[maxn],cnt[maxn]={0};
int n,m,tot=0,flag=1,fh=0,l=1,ans=0;

inline ll read()
{
	ll x=0,f=1;
	char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*f;
}

inline void writ(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) writ(x/10);
	putchar(x%10+'0');
}
inline void write(int x){writ(x);putchar(' ');}

int main()
{
	n=read(),m=read();
	for (int i=1;i<=n;++i) a[i]=read();
	for (int i=1;i<=m;++i) {x[i]=read();if (x[i]==0) ++tot;}
	for (int i=1;;++i)
	{
		++cnt[a[i]];
		if (cnt[a[i]]==x[a[i]]) ++tot;
		if (tot==m) {flag=0;break;}
		fh=i;
	}
	if (flag){write(-1);return 0;}
	for (int i=1;i<=m;++i) ans+=cnt[i]-x[i];
	int mx=ans;
	for (int i=fh+1;i<=n;++i)
	{
		while (cnt[a[l]]>x[a[l]]) --mx,--cnt[a[l]],++l;
		if (mx<ans) ans=mx;
		++cnt[a[i]];
	}
	write(ans);
	return 0;
}


#include<bits/stdc++.h>
#define maxn 200007
#define ll long long int
using namespace std;

int a[maxn],x[maxn],cnt[maxn]={0};
int n,m,tot=0,flag=1,fh=0,l=1,ans=0;

inline ll read()
{
	ll x=0,f=1;
	char ch=getchar();
	while (ch<'0'||ch>'9'){if (ch=='-') f=-1;ch=getchar();}
	while (ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
	return x*f;
}

inline void writ(int x)
{
	if(x<0) putchar('-'),x=-x;
	if(x>9) writ(x/10);
	putchar(x%10+'0');
}
inline void write(int x){writ(x);putchar(' ');}

int main()
{
	n=read(),m=read();
	for (int i=1;i<=n;++i) a[i]=read();
	for (int i=1;i<=m;++i) {x[i]=read();if (x[i]==0) ++tot;}
	for (int i=1;i<=n;++i)
	{
		++cnt[a[i]];
		if (cnt[a[i]]==x[a[i]]) ++tot;
		if (tot==m) {flag=0,fh=i;break;}
	}
	if (flag){write(-1);return 0;}
	for (int i=1;i<=m;++i) ans+=cnt[i]-x[i];
	int mx=ans;
	for (int i=fh+1;i<=n;++i)
	{
		while (cnt[a[l]]>x[a[l]]) --mx,--cnt[a[l]],++l;
		if (mx<ans) ans=mx;
		++cnt[a[i]],++mx;
	}
	while (cnt[a[l]]>x[a[l]]) --mx,--cnt[a[l]],++l;
	if (mx<ans) ans=mx;
	write(ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int debug_num=0;
const int maxn=200000+20;
int m[maxn],n[maxn],mf[maxn];
int m1,n1;
bool check(int a[])
{
    int i;
    for(i=1;i<=m1;i++){
        if(a[i]>=m[i])continue;
        else break;
    }
    if(i==m1+1)return true;
    else return false;
}
int aaa(int a[])
{
    int i,cnt;
    for(i=1;i<=m1;i++)cnt+=a[i]-m[i];
    return cnt;
}
int hhh1(int &s)
{
    int i,e;
    int k[m1+1];
    for(i=0;i<m1+1;i++)k[i]=0;
    for(i=s;!check(k)&&i<=n1;i++){
        int c=n[i];
        k[c]++;
    }
    if(check(k)){
        e=i-1;
        for(int i=1;i<=m1;i++)mf[i]=k[i];
    }
    else {i=-1;return i;}
    for(i=s;check(k)&&i<=n1;i++){
        int c=n[i];
        k[c]--;
    }
    s=i-1;
    return e;
}//从起点s开始读入光剑类型，直到满足条件为止，若在结束前都没满足，返回-1，否则返回结束位置
int main()
{
    int i;
    scanf("%d %d",&n1,&m1);
    for(i=1;i<=n1;i++)scanf("%d",&n[i]);//读入光剑类型
    for(i=1;i<=m1;i++)scanf("%d",&m[i]);//读入需要光剑数量
    int s=1,lenth=0,cnt=9999999;
    for(i=1;i<=m1;i++)lenth+=m[i];//所需连续系列的长度
    while(s<=n1-lenth+1){
        int k=hhh1(s);
        if(k>0){
                if(cnt>(k-s+1-lenth))cnt=k-s+1-lenth;
                s=s+1;
        }
        else{
            break;
        }
    }
    if(cnt>=maxn+1000)cnt=-1;
    printf("%d",cnt);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[200020],b[200020];
int c[200020],lenth,falsei;
bool check()
{
    for(int i=1;i<=m;i++){
        if(c[i]<=0)return false;
    }
    return true;
}
int main(void)
{
    int i;
    cin>>n>>m;
    lenth=falsei=0;
    for(i=1;i<=n;i++)scanf("%d",&a[i]);
    for(i=1;i<=m;i++)scanf("%d",&b[i]);
    for(i=1;i<=m;i++)lenth+=b[i];
    for(i=1;i<=m;i++)c[i]=-b[i]+1;
    int s=1,e=1,cnt=99999999;
    for(i=1;i<=n;i++){
        c[a[i]]++;
        if(check())break;
    }
    if(i==n+1){
        printf("-1");
        return 0;
    }
    else {
        e=i;
        cnt=min(cnt,e-s+1-lenth);
        while(e<n){
            if(falsei==0){
                c[a[s]]--;
                if(c[i]<=0){
                        falsei=a[s];
                        cnt=min(cnt,e-s-lenth);
                        }
                s++;
            }
            else {
                e++;
                c[a[e]]++;
                if(falsei==a[e]){
                        falsei=0;
                        cnt=min(cnt,e-s+1-lenth);
                }
            }
        }
        printf("%d",cnt);
        return 0;
    }
}


#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[200020],b[200020];
int c[200020],lenth,falsei;
bool check()
{
    for(int i=1;i<=m;i++){
        if(c[i]<=0)return false;
    }
    return true;
}
int main(void)
{
    int i;
    cin>>n>>m;
    lenth=falsei=0;
    for(i=1;i<=n;i++)scanf("%d",&a[i]);
    for(i=1;i<=m;i++)scanf("%d",&b[i]);
    for(i=1;i<=m;i++)lenth+=b[i];
    for(i=1;i<=m;i++)c[i]=-b[i]+1;
    int s=1,e=1,cnt=99999999;
    for(i=1;i<=n;i++){
        c[a[i]]++;
        if(check())break;
    }
    if(i==n+1){
        printf("-1");
        return 0;
    }
    else {
        e=i;
        cnt=min(cnt,e-s+1-lenth);
        while(e<n||(e==n&&falsei==0)){
            if(falsei==0){
                c[a[s]]--;
                if(c[a[s]]<=0)falsei=a[s];
                else cnt=min(cnt,e-s-lenth);
                s++;
            }
            else {
                e++;
                c[a[e]]++;
                if(falsei==a[e]){
                        falsei=0;
                        cnt=min(cnt,e-s+1-lenth);
                }
            }
        }
        printf("%d",cnt);
        return 0;
    }
}


#include<bits/stdc++.h>
using namespace std;
int n,m;
int a[200020],b[200020];
int c[200020],lenth,falsei;
bool check()
{
    for(int i=1;i<=m;i++){
        if(c[i]<=0)return false;
    }
    return true;
}
int main(void)
{
    int i;
    cin>>n>>m;
    lenth=falsei=0;
    for(i=1;i<=n;i++)scanf("%d",&a[i]);
    for(i=1;i<=m;i++)scanf("%d",&b[i]);
    for(i=1;i<=m;i++)lenth+=b[i];
    for(i=1;i<=m;i++)c[i]=-b[i]+1;
    int s=1,e=1,cnt=99999999;
    for(i=1;i<=n;i++){
        c[a[i]]++;
        if(check())break;
    }
    if(i==n+1){
        printf("-1");
        return 0;
    }
    else {
        e=i;
        cnt=min(cnt,e-s+1-lenth);
        while(e<n){
            if(falsei==0){
                c[a[s]]--;
                if(c[i]<=0){
                        falsei=a[s];
                        cnt=min(cnt,e-s-lenth);
                        }
                s++;
            }
            else {
                e++;
                c[a[e]]++;
                if(falsei==a[e]){
                        falsei=0;
                        cnt=min(cnt,e-s+1-lenth);
                }
            }
        }
        printf("%d",cnt);
    }
}


#include<bits/stdc++.h>
using namespace std;
int debug_num=0;
const int maxn=200000+20;
int m[maxn],n[maxn],mf[maxn];
int m1,n1;
bool check(int a[])
{
    int i;
    for(i=1;i<=m1;i++){
        if(a[i]>=m[i])continue;
        else break;
    }
    if(i==m1+1)return true;
    else return false;
}
int aaa(int a[])
{
    int i,cnt;
    for(i=1;i<=m1;i++)cnt+=a[i]-m[i];
    return cnt;
}
int hhh1(int s)
{
    int i;
    int k[m1+1];
    for(i=0;i<m1+1;i++)k[i]=0;
    for(i=s;!check(k)&&i<=n1;i++){
        int c=n[i];
        k[c]++;
    }
    if(check(k)){
        i=i-1;
        for(int i=1;i<=m1;i++)mf[i]=k[i];
    }
    else i=-1;
    return i;
}//从起点s开始读入光剑类型，直到满足条件为止，若在结束前都没满足，返回-1，否则返回结束位置
int hhh2(int s)
{
    int i;
    int k[m1+1];
    for(i=0;i<m1+1;i++)k[i]=0;
    for(i=s;!check(k)&&i>0;i--){
        int c=n[i];
        k[c]++;
    }
    if(check(k)){
        i=i+1;
        for(int i=1;i<=m1;i++)mf[i]=k[i];
    }
    else i=-1;
    return i;
}//从终点s开始读入光剑类型，直到满足条件为止，若在结束前都没满足，返回-1，否则返回结束位置。
int main()
{
    int i;
    scanf("%d %d",&n1,&m1);
    for(i=1;i<=n1;i++)scanf("%d",&n[i]);//读入光剑类型
    for(i=1;i<=m1;i++)scanf("%d",&m[i]);//读入需要光剑数量
    int s=1,lenth=0,cnt=9999999;
    for(i=1;i<=m1;i++)lenth+=m[i];//所需连续系列的长度
    while(s<=n1-lenth+1){
        int k=hhh1(s),k1;
        if(k>0){
                k1=hhh2(k);
                if(cnt>(k-k1+1-lenth))cnt=k-k1+1-lenth;
                s=k1+1;
        }
        else{
            break;
        }
    }
    if(cnt>=maxn+1000)cnt=-1;
    printf("%d",cnt);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int debug_num=0;
const int maxn=200000+20;
int m[maxn],n[maxn],mf[maxn];
int m1,n1;
bool check(int a[])
{
    int i;
    for(i=1;i<=m1;i++){
        if(a[i]>=m[i])continue;
        else break;
    }
    if(i==m1+1)return true;
    else return false;
}
bool check2(int a[])
{
    int i;
    for(i=1;i<=m1;i++){
        if(a[i]>m[i])return true;
    }
    return false;
}
int hhh1(int &s)
{
    int i,e;
    int k[m1+1];
    for(i=0;i<m1+1;i++)k[i]=0;
    for(i=s;!check(k)&&i<=n1;i++){
        int c=n[i];
        k[c]++;
    }
    if(check(k)){
        e=i-1;
        for(int i=1;i<=m1;i++)mf[i]=k[i];
    }
    else e=-1;
    for(i=s;check(k)&&i<=n1;i++){
        int c=n[i];
        k[c]--;
    }
    s=i-1;
    for(i=0;i<m1+1;i++)k[i]=0;
    for(i=s;!check2(k)&&i<=n1;i++){
        int c=n[i];
        k[c]++;
    }
    return e;
}//从起点s开始读入光剑类型，直到满足条件为止，若在结束前都没满足，返回-1，否则返回结束位置
int main()
{
    int i;
    scanf("%d %d",&n1,&m1);
    for(i=1;i<=n1;i++)scanf("%d",&n[i]);//读入光剑类型
    for(i=1;i<=m1;i++)scanf("%d",&m[i]);//读入需要光剑数量
    int s=1,lenth=0,cnt=9999999;
    for(i=1;i<=m1;i++)lenth+=m[i];//所需连续系列的长度
    while(s<=n1-lenth+1){
        int k=hhh1(s);
        if(k>0){
                if(cnt>(k-s+1-lenth))cnt=k-s+1-lenth;
                s=s+2;
        }
        else{
            break;
        }
    }
    if(cnt>=maxn+1000)cnt=-1;
    printf("%d",cnt);
    return 0;
}


#include<cstdio>

const int Max_n=2e5;
int n,m,color[Max_n+5],cnt[Max_n+5],k[Max_n+5];
int main() {
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++)
		scanf("%d",&color[i]);
	int un_use=m,ans=n+1,sum=0;
	for(int i=1;i<=m;i++) {
		scanf("%d",&k[i]);
		sum+=k[i];
	}
	for(int bin=0,end=0;end<n;end++) {
		cnt[color[end]]++;
		if(cnt[color[end]]==k[color[end]])
			un_use--;
		while(cnt[color[bin]]>k[color[bin]])
			cnt[color[bin++]]--;
		if(un_use==0&&ans>(end-bin+1)-sum)
			ans=(end-bin+1)-sum;
	}
	printf("%d",(ans>n)?(-1):ans);
	return 0;
}


#include<cstdio>

const int Max_n=2e5;
int n,m,color[Max_n+5],cnt[Max_n+5],k[Max_n+5];
int main() {
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++)
		scanf("%d",&color[i]);
	int un_use=m,ans=n+1,sum=0;
	for(int i=1;i<=m;i++) {
		scanf("%d",&k[i]);
		sum+=k[i];
	}
	for(int bin=0,end=0;end<n;end++) {
		cnt[color[end]]++;
		if(cnt[color[end]]==k[color[end]])
			un_use--;
		while(cnt[color[bin]]>k[color[bin]])
			cnt[color[bin++]]--;
		if(un_use==0&&ans>(end-bin+1)-sum)
			ans=(end-bin+1)-sum;
	}
	printf("%d",(ans>n)?-1:ans);
	return 0;
}


#include<cstdio>

const int Max_n=2e5;
int n,m,color[Max_n+5],cnt[Max_n+5],k[Max_n+5];
int main() {
	scanf("%d %d",&n,&m);
	for(int i=0;i<n;i++)
		scanf("%d",&color[i]);
	int un_use=0,ans=n+1,sum=0;
	for(int i=1;i<=m;i++) {
		scanf("%d",&k[i]);
		sum+=k[i];
		un_use+=(k[i]>0);
	}
	for(int bin=0,end=0;end<n;end++) {
		cnt[color[end]]++;
		if(cnt[color[end]]==k[color[end]])
			un_use--;
		while(cnt[color[bin]]>k[color[bin]])
			cnt[color[bin++]]--;
		if(un_use==0&&ans>(end-bin+1)-sum)
			ans=(end-bin+1)-sum;
	}
	printf("%d",(ans>n)?(-1):ans);
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
int read()
{
	char ch=getchar();int f=0,x=1;
	while(ch<'0'||ch>'9'){if(ch=='-') x=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){f=(f<<1)+(f<<3)+ch-'0';ch=getchar();}
	return f*x;
}
int num[200005],sum;
int a[200005],k[2000005];
int n,minn=1000000000,m;
int main()
{
	n=read();m=read();
	for(int i=1;i<=n;i++) a[i]=read();
	for(int i=1;i<=m;i++) k[i]=read();
	for(int i=1;i<=m;i++)
	{
		if(k[i]==0) sum++;
	}
	int l=0,r=1;
	while(l<=n)
	{
		while(l+1>r-1&&r<=n)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a[r]]) sum++;
			r++;
		}
		num[a[l]]--;
		if(num[a[l]]==k[a[l]]-1&&a[l]!=0) sum--;
		while(r<=n&&sum!=m)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a[r]]) sum++;
			r++;
		}
		//cout<<l<<" "<<r<<" "<<sum<<endl;
		if(sum==m)
		{
			minn=min(minn,r-l-1);
		}
		l++;
	}
	int temp=0;
	for(int i=1;i<=m;i++)
	temp+=k[i];
	if(minn>n) puts("-1");
	else cout<<minn-temp;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
int read()
{
	char ch=getchar();int f=0,x=1;
	while(ch<'0'||ch>'9'){if(ch=='-') x=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){f=(f<<1)+(f<<3)+ch-'0';ch=getchar();}
	return f*x;
}
int num[100005],sum;
int a[100005],k[1000005];
int n,minn=1000000000,m;
int main()
{
	n=read();m=read();
	for(int i=1;i<=n;i++) a[i]=read();
	for(int i=1;i<=m;i++) k[i]=read();
	int l=0,r=1;
	while(l<=n)
	{
		num[a[l]]--;
		if(num[a[l]]==k[a[l]]-1&&a[l]!=0) sum--;
		while(r<=n&&sum!=m)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a[r]]) sum++;
			r++;
		}
		//cout<<l<<" "<<r<<" "<<sum<<endl;
		if(sum==m)
		{
			minn=min(minn,r-l-1);
		}
		l++;
	}
	int temp=0;
	for(int i=1;i<=m;i++)
	temp+=k[i];
	if(minn>n) puts("-1");
	else cout<<minn-temp;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
int read()
{
	char ch=getchar();int f=0,x=1;
	while(ch<'0'||ch>'9'){if(ch=='-') x=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){f=(f<<1)+(f<<3)+ch-'0';ch=getchar();}
	return f*x;
}
int num[100005],sum;
int a[100005],k[1000005];
int n,minn=1000000000,m;
int main()
{
	n=read();m=read();
	for(int i=1;i<=n;i++) a[i]=read();
	for(int i=1;i<=m;i++) k[i]=read();
	for(int i=1;i<=m;i++)
	{
		if(k[i]==0) sum++;
	}
	int l=0,r=1;
	while(l<=n)
	{
		while(l+1>r-1&&r<=n)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a[r]]) sum++;
			r++;
		}
		num[a[l]]--;
		if(num[a[l]]==k[a[l]]-1&&a[l]!=0) sum--;
		while(r<=n&&sum!=m)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a1 1[r]]) sum++;
			r++;
		}
		//cout<<l<<" "<<r<<" "<<sum<<endl;
		if(sum==m)
		{
			minn=min(minn,r-l-1);
		}
		l++;
	}
	int temp=0;
	for(int i=1;i<=m;i++)
	temp+=k[i];
	if(minn>n) puts("-1");
	else cout<<minn-temp;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
int read()
{
	char ch=getchar();int f=0,x=1;
	while(ch<'0'||ch>'9'){if(ch=='-') x=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){f=(f<<1)+(f<<3)+ch-'0';ch=getchar();}
	return f*x;
}
int num[100005],sum;
int a[100005],k[1000005];
int n,minn=1000000000,m;
int main()
{
	n=read();m=read();
	for(int i=1;i<=n;i++) a[i]=read();
	for(int i=1;i<=m;i++) k[i]=read();
	for(int i=1;i<=m;i++)
	{
		if(k[i]==0) sum++;
	}
	int l=0,r=1;
	while(l<=n)
	{
		num[a[l]]--;
		if(num[a[l]]==k[a[l]]-1&&a[l]!=0) sum--;
		while(r<=n&&sum!=m)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a[r]]) sum++;
			r++;
		}
		//cout<<l<<" "<<r<<" "<<sum<<endl;
		if(sum==m)
		{
			minn=min(minn,r-l-1);
		}
		l++;
	}
	int temp=0;
	for(int i=1;i<=m;i++)
	temp+=k[i];
	if(minn>n) puts("-1");
	else cout<<minn-temp;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define ll long long
using namespace std;
int read()
{
	char ch=getchar();int f=0,x=1;
	while(ch<'0'||ch>'9'){if(ch=='-') x=-1;ch=getchar();}
	while(ch>='0'&&ch<='9'){f=(f<<1)+(f<<3)+ch-'0';ch=getchar();}
	return f*x;
}
int num[100005],sum;
int a[100005],k[1000005];
int n,minn=1000000000,m;
int main()
{
	n=read();m=read();
	for(int i=1;i<=n;i++) a[i]=read();
	for(int i=1;i<=m;i++) k[i]=read();
	for(int i=1;i<=m;i++)
	{
		if(k[i]==0) sum++;
	}
	int l=0,r=1;
	while(l<=n)
	{
		while(l+1>r-1&&r<=n)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a[r]]) sum++;
			r++;
		}
		num[a[l]]--;
		if(num[a[l]]==k[a[l]]-1&&a[l]!=0) sum--;
		while(r<=n&&sum!=m)
		{
			num[a[r]]++;
			if(num[a[r]]==k[a[r]]) sum++;
			r++;
		}
		//cout<<l<<" "<<r<<" "<<sum<<endl;
		if(sum==m)
		{
			minn=min(minn,r-l-1);
		}
		l++;
	}
	int temp=0;
	for(int i=1;i<=m;i++)
	temp+=k[i];
	if(minn>n) puts("-1");
	else cout<<minn-temp;
}


#include <bits/stdc++.h>

using namespace std;

inline void Boost() {
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
}
typedef long long int ll;
typedef long double ld;

int main() {
	Boost();

	int n, k;
	cin >> n >> k;

	vector < int > v(n);
	for(auto &x: v) {
		cin >> x;
		--x;
	}

	vector < int > K(k), frecv(k, 0);
	for(auto &x: K) cin >> x;

	int sum = 0;
	int good = 0;
	for(auto x: K) {
		sum += x;
		if(x == 0) ++good;
	}

	int lo;
	lo = 0;

	int best = INT_MAX;
	for(int i = 0; i < n; ++i) {
		++frecv[v[i]];
		if(frecv[v[i]] == K[v[i]]) ++good;
		while(frecv[v[lo]] > K[v[lo]]) {
			--frecv[v[lo]];
			++lo;
		}

		if(good == k) {
			best = min(best, i - lo + 1);
		}
	}

	if(best == INT_MAX) {
		best = -1;
	} else {
		best -= sum;
	}

	cout << best;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

inline void Boost() {
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
}
typedef long long int ll;
typedef long double ld;

vector < int > K, frecv, v;

int main() {
	Boost();

	int n, k;
	cin >> n >> k;

	v.resize(n);
	for(auto &x: v) {
		cin >> x;
		--x;
	}

	K.resize(k); frecv.resize(k);
	for(auto &x: K) cin >> x;

	int sum = 0;
	int good = 0;
	for(auto x: K) {
		sum += x;
		if(x == 0) ++good;
	}

	int lo;
	lo = 0;

	int best = INT_MAX;
	for(int i = 0; i < n; ++i) {
		++frecv[v[i]];
		if(frecv[v[i]] == K[v[i]]) ++good;
		while(frecv[v[lo]] > K[v[lo]]) {
			--frecv[v[lo]];
			++lo;
		}

		if(good == k) {
			best = min(best, i - lo + 1);
		}
	}

	if(best == INT_MAX) {
		best = -1;
	} else {
		best -= sum;
	}

	cout << best;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

inline void Boost() {
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
}
typedef long long int ll;
typedef long double ld;

const int INF = 2e9;
vector < int > K, frecv, v;

int main() {
	Boost();

	int n, k;
	cin >> n >> k;

	v.resize(n);
	for(auto &x: v) {
		cin >> x;
		--x;
	}

	K.resize(k + 5); frecv.resize(k + 5);
	for(int i = 0; i < k; ++i) cin >> K[i];

	int sum = 0;
	int good = 0;
	for(int i = 0; i < k; ++i) {
		sum += K[i];
		if(K[i] == 0) ++good;
	}

	int lo = 0;

	int best = INF;
	for(int i = 0; i < n; ++i) {
		++frecv[v[i]];
		if(frecv[v[i]] == K[v[i]]) ++good;
		while(frecv[v[lo]] > K[v[lo]]) {
			--frecv[v[lo]];
			++lo;
		}

		if(good == k) {
			best = min(best, i - lo + 1);
		}
	}

	if(best == INF) {
		best = -1;
	} else {
		best -= sum;
	}

	cout << best;
	return 0;
}


#include <bits/stdc++.h>

using namespace std;

inline void Boost() {
	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
}
typedef long long int ll;
typedef long double ld;

const int INF = 2e9;
const int NMax = 2e5 + 50;

int K[NMax], frecv[NMax], v[NMax];

int main() {
	Boost();

	int n, k;
	cin >> n >> k;

	for(int i = 0; i < n; ++i) {
		cin >> v[i];
		--v[i];
	}

	for(int i = 0; i < k; ++i) cin >> K[i];

	int sum = 0;
	int good = 0;
	for(int i = 0; i < k; ++i) {
		sum += K[i];
		if(K[i] == 0) ++good;
	}

	int lo = 0;

	int best = INF;
	for(int i = 0; i < n; ++i) {
		++frecv[v[i]];
		if(frecv[v[i]] == K[v[i]]) ++good;
		while(frecv[v[lo]] > K[v[lo]]) {
			--frecv[v[lo]];
			++lo;
		}

		if(good == k) {
			best = min(best, i - lo + 1);
		}
	}

	if(best == INF) {
		best = -1;
	} else {
		best -= sum;
	}

	cout << best;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX = 200005;
#define inf 0x3f3f3f3f
int a[MAX],k[MAX];
int cnt1[MAX],len = 0;
int cnt2[MAX];
int n,m;
bool judge()
{
    for (int i=1; i<=m; i++)
    {
        if (cnt2[i]<cnt1[i])
            return false;
    }
    return true;
}

int main()
{
    scanf("%d%d",&n,&m);
    for (int i=0; i<n; ++i)
        scanf("%d",&a[i]);
    for (int i=1; i<=m; ++i)
    {
        scanf("%d",&cnt1[i]);
        len += cnt1[i];
    }
    if (len==0)
    {
        printf("0\n");
        return 0;
    }
    int st = 0,en = len-1;
    for (int i=0; i<=en; ++i)
        cnt2[a[i]] ++;
    int minn = inf;
    while (en<n)
    {
        while (!judge()&&en<n)
        {
            en++;
            cnt2[a[en]]++;
        }
        if (en==n) break;
        if(minn>en-st+1-len) minn = en-st+1-len;
        cnt2[a[st]]--;
        st++;
        if(judge())
        {
            while(en-st+1<=len&&cnt2[a[st]]>=cnt1[a[st]])
            {
                if(minn>en-st+1-len) minn = en-st+1-len;
                cnt2[a[st]]--;
                st++;
            }
        }
    }
    if (minn==inf)
        printf("-1\n");
    else printf("%d\n",max(minn,0));
    return 0;
}


#include<cstdio>
#include<vector>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
#define mp                          make_pair
#define pb							push_back
#define sz(x)                       int(x.size())
#define all(x)                      x.begin(),x.end()
#define lson                        rt<<1,l,m
#define rson                        rt<<1|1,m+1,r
#define rep(i,s,e)                  for (int i=s;i<=e;i++)
#define rev(i,s,e)                  for (int i=s;i>=e;i--)

typedef long long LL;
typedef pair<int, int> PII;
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
const int MAXN = 2e5 + 5;

int n,m,num,cnt,ans=INF;
int a[MAXN], b[MAXN], c[MAXN];
int main()
{
#ifdef LOCAL
    freopen("in.txt","r",stdin);
    freopen("out.txt","w",stdout);
#endif
    scanf("%d%d",&n,&m);
    rep(i,1,n) scanf("%d",&a[i]);
    rep(i,1,m)
    {
        scanf("%d",&b[i]);
        if (b[i] == 0) cnt++;
        num+= b[i];
    }
    int l = 1, r = 1;
    for (; r<=n; r++)
    {
        c[ a[r] ]++;
        if (c[ a[r] ] == b[ a[r] ])
        {
            cnt++;
            if (cnt == m) break;
        }
    }
    if (r==n+1) return 0*puts("-1");
    while (c[ a[l] ] > b[ a[l] ])
    {
        c[ a[l] ] --;
        l++;
    }
    ans = min(ans, r-l+1-num);
    for (r++; r<=n; r++)
    {
        c[ a[r] ]++;
        if (a[r] == a[l])
        {
            while (c[ a[l] ] > b[ a[l] ])
            {
                c[ a[l] ] --;
                l++;
            }
            ans = min(ans, r-l+1-num);
        }
    }
    printf("%d\n",max(ans,0));
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX = 200005;
#define inf 0x3f3f3f3f
int a[MAX],k[MAX];
int cnt1[MAX],len = 0;
int cnt2[MAX];
int n,m;
bool judge()
{
    for (int i=1; i<=m; i++)
    {
        if (cnt2[i]<cnt1[i])
            return false;
    }
    return true;
}

int main()
{
    scanf("%d%d",&n,&m);
    for (int i=0; i<n; ++i)
        scanf("%d",&a[i]);
    for (int i=1; i<=m; ++i)
    {
        scanf("%d",&cnt1[i]);
        len += cnt1[i];
    }
    if (len==0)
    {
        printf("0\n");
        return 0;
    }
    int st = 0,en = len-1;
    for (int i=0; i<=en; ++i)
        cnt2[a[i]] ++;
    int minn = inf;
    while (en<n)
    {
        while (!judge()&&en<n)
        {
            en++;
            cnt2[a[en]]++;
        }
        if (en==n) break;
        if(minn>en-st+1-len) minn = en-st+1-len;
        cnt2[a[st]]--;
        st++;
        if(judge())
        {
            while(en-st+1<=len&&cnt2[a[st]]>=cnt1[a[st]])
            {
                if(minn>en-st+1-len) minn = en-st+1-len;
                cnt2[a[st]]--;
                st++;
            }
        }
    }
    if (minn==inf)
        printf("-1\n");
    else printf("%d\n",minn);
    return 0;
}


#include<bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;
#define ll long long
//#define lld I64d
const int N = 1e6+5;
const int INF = 0xfffffff;
/*
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
*/

template<typename T>
void scan(T& x)
{
    x=0;
    char ch=getchar();
    while(ch==' '||ch=='\n')ch=getchar();
    do{
        x=10*x+ch-'0';
        ch=getchar();
    }while(ch>='0'&&ch<='9');
}

template<typename T>
void print(T x)
{
    if(x<=9)putchar(x+'0');
    else
    {
        print(x/10);
        putchar((x%10)+'0');
    }
}

int n,m;
int a[N],b[N],c[N];

void solve()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",a+i);
    }
    int sum=0;
    int cnt=0;
    for(int i=1;i<=m;i++)
    {
        scanf("%d",b+i);
        sum+=b[i];
        if(!b[i])cnt++;
    }
    int ans=0xfffffff;
    for(int i=1,j=1;i<=n;i++)
    {
        while(j<=n&&cnt!=m)
        {
            c[a[j]]++;
            if(c[a[j]]==b[a[j++]])cnt++;
        }
        if(cnt==m)
        {
            ans=min(ans,j-i-sum);
        }
        if(j>n)break;
        c[a[i]]--;
        if(c[a[i]]==b[a[i]]-1)cnt--;
    }
    if(ans==0xfffffff)printf("-1\n");
    else printf("%d\n",ans);
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    solve();
    return 0;
}


#include<bits/stdc++.h>
#pragma warning(disable:4996)
using namespace std;
#define ll long long
//#define lld I64d
const int N = 1e6+5;
const int INF = 0xfffffff;
/*
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
*/

template<typename T>
void scan(T& x)
{
    x=0;
    char ch=getchar();
    while(ch==' '||ch=='\n')ch=getchar();
    do{
        x=10*x+ch-'0';
        ch=getchar();
    }while(ch>='0'&&ch<='9');
}

template<typename T>
void print(T x)
{
    if(x<=9)putchar(x+'0');
    else
    {
        print(x/10);
        putchar((x%10)+'0');
    }
}

int n,m;
int a[N],b[N],c[N];

void solve()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
    {
        scanf("%d",a+i);
    }
    int sum=0;
    int cnt=0;
    for(int i=1;i<=m;i++)
    {
        scanf("%d",b+i);
        sum+=b[i];
        if(!b[i])cnt++;
    }
    int ans=0xfffffff;
    for(int i=1,j=0;i<=n;i++)
    {
        while(j<=n&&cnt!=m)
        {
            c[a[++j]]++;
            if(c[a[j]]==b[a[j]])cnt++;
        }
        if(cnt==m)
        {
            ans=min(ans,j-i+1-sum);
        }
        if(j>n)break;
        c[a[i]]--;
        if(c[a[i]]==b[a[i]]-1)cnt--;
    }
    if(ans==0xfffffff)printf("-1\n");
    else printf("%d\n",ans);
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("in.txt","r",stdin);
#endif
    solve();
    return 0;
}


#include "bits/stdc++.h"
using namespace std;
int a[200010], b[200010];
int cnt[200010];

int main(int argc, char const *argv[])
{
	int n, m, tot = 0;
	scanf("%d %d", &n, &m);
	for(int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	for(int i = 1; i <= m; i++) {
		scanf("%d", &b[i]);
		tot += b[i];
	}
	int l = 1;
	set <int> s;
	for(int i = 1; i <= m; i++) {
		if(b[i]) s.insert(i);
	}
	int ans = n + 10;
	for(int i = 1; i <= n; i++) {
		cnt[a[i]] += 1;
		if(cnt[a[i]] >= b[a[i]]) {
			s.erase(a[i]);
		}
		if(s.empty()) {
			while(l < i && cnt[a[l]] > b[a[l]]) {
				cnt[a[l]] -= 1;
				++l;
			}
			ans = min(ans, (i - l + 1) - tot);
		}
	}
	if(ans > n) ans = -1;
	printf("%d\n", ans);
	return 0;
}


#include "bits/stdc++.h"
using namespace std;
int a[200010], b[200010];
int cnt[200010];

int main(int argc, char const *argv[])
{
	int n, m, tot = 0;
	scanf("%d %d", &n, &m);
	for(int i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
	}
	for(int i = 1; i <= m; i++) {
		scanf("%d", &b[i]);
		tot += b[i];
	}
	int l = 1;
	set <int> s;
	for(int i = 1; i <= m; i++) {
		s.insert(i);
	}
	int ans = n + 10;
	for(int i = 1; i <= n; i++) {
		cnt[a[i]] += 1;
		if(cnt[a[i]] >= b[a[i]]) {
			s.erase(a[i]);
		}
		if(s.empty()) {
			while(l < i && cnt[a[l]] > b[a[l]]) {
				cnt[a[l]] -= 1;
				++l;
			}
			ans = min(ans, (i - l + 1) - tot);
		}
	}
	if(ans > n) ans = -1;
	printf("%d\n", ans);
	return 0;
}


#include<bits/stdc++.h>
#define FIO "F2"
using namespace std;
typedef long long ll;
inline int read()
{
	int x=0,f=1;char c=getchar();
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){x=x*10+c-'0';c=getchar();}
	return x*f;
}

template<typename T> inline void Min(T &x,T y) {if(x>y) x=y;}
template<typename T> inline void Max(T &x,T y) {if(x<y) x=y;}

const int maxn=2e5+10;
int n,m,a[maxn],k[maxn],cnt[maxn],ans=maxn,S=0;

int main()
{
#ifdef dxymaster
	freopen(FIO".in","r",stdin);
	freopen(FIO".out","w",stdout);
#endif

	n=read(),m=read();
	for(int i=1;i<=n;i++) cnt[a[i]=read()]++;
	for(int i=1;i<=m;i++) k[i]=read(),S+=k[i];
	for(int i=1;i<=m;i++) if(cnt[i]<k[i]) return puts("-1"),0;
	int l=1,r=0;memset(cnt,0,sizeof(cnt));
	for(int i=1;i<=m;i++)
		while(cnt[i]<k[i]&&r<n) ++cnt[a[++r]];
	while(r<=n)
	{
		while(cnt[a[l]]-1>=k[a[l]]&&l<r) --cnt[a[l]],++l;
		Min(ans,r-l+1-S);++r;
	}

	cout<<ans<<endl;
#ifdef dxymaster
	cerr << "TIME: " << (double)clock() / CLOCKS_PER_SEC << "s		It Runs So Fast!" << endl;
#endif
	return 0;
}


#include<bits/stdc++.h>
#define FIO "F2"
using namespace std;
typedef long long ll;
inline int read()
{
	int x=0,f=1;char c=getchar();
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){x=x*10+c-'0';c=getchar();}
	return x*f;
}

template<typename T> inline void Min(T &x,T y) {if(x>y) x=y;}
template<typename T> inline void Max(T &x,T y) {if(x<y) x=y;}

const int maxn=5e5+10;
int n,m,a[maxn],k[maxn],cnt[maxn],ans=0,S=0;

int main()
{
#ifdef dxymaster
	freopen(FIO".in","r",stdin);
	freopen(FIO".out","w",stdout);
#endif

	n=read(),m=read();ans=maxn;
	for(int i=1;i<=n;i++) cnt[a[i]=read()]++;
	for(int i=1;i<=m;i++) k[i]=read(),S+=k[i];
	for(int i=1;i<=m;i++) if(cnt[i]<k[i]) return puts("-1"),0;
	int l=1,r=0;memset(cnt,0,sizeof(cnt));
	if(!S) return puts("0"),0;
	for(int i=1;i<=m;i++)
		while(cnt[i]<k[i]&&r<n) ++cnt[a[++r]];
	while(r<=n)
	{
		while(cnt[a[l]]-1>=k[a[l]]&&l<r) --cnt[a[l]],++l;
		Min(ans,r-l+1-S);++r;
	}
	if(ans==maxn) puts("-1");
	else cout<<ans<<endl;
#ifdef dxymaster
	cerr << "TIME: " << (double)clock() / CLOCKS_PER_SEC << "s		It Runs So Fast!" << endl;
#endif
	return 0;
}


#include<bits/stdc++.h>
#define FIO "F2"
using namespace std;
typedef long long ll;
inline int read()
{
	int x=0,f=1;char c=getchar();
	while(!isdigit(c)){if(c=='-')f=-1;c=getchar();}
	while(isdigit(c)){x=x*10+c-'0';c=getchar();}
	return x*f;
}

template<typename T> inline void Min(T &x,T y) {if(x>y) x=y;}
template<typename T> inline void Max(T &x,T y) {if(x<y) x=y;}

const int maxn=5e5+10;
int n,m,a[maxn],k[maxn],cnt[maxn],ans=maxn,S=0;

int main()
{
#ifdef dxymaster
	freopen(FIO".in","r",stdin);
	freopen(FIO".out","w",stdout);
#endif

	n=read(),m=read();
	for(int i=1;i<=n;i++) cnt[a[i]=read()]++;
	for(int i=1;i<=m;i++) k[i]=read(),S+=k[i];
	for(int i=1;i<=m;i++) if(cnt[i]<k[i]) return puts("-1"),0;
	int l=1,r=0;memset(cnt,0,sizeof(cnt));
	if(!S) return puts("0"),0;
	for(int i=1;i<=m;i++)
		while(cnt[i]<k[i]&&r<n) ++cnt[a[++r]];
	while(r<=n)
	{
		while(cnt[a[l]]-1>=k[a[l]]&&l<r) --cnt[a[l]],++l;
		Min(ans,r-l+1-S);++r;
	}

	cout<<ans<<endl;
#ifdef dxymaster
	cerr << "TIME: " << (double)clock() / CLOCKS_PER_SEC << "s		It Runs So Fast!" << endl;
#endif
	return 0;
}


from collections import defaultdict

numbers = defaultdict(int)
for i in range(int(input())):
    operation, operator = input().split()
    temp = ''
    for char in operator:
        if char in ['1', '3', '5', '7', '9']:
            temp += '1'
        else:
            temp += '0'

    temp2 = int(temp, 2)

    if operation == '+':
        numbers[temp2] += 1
    elif operation == '-':
        numbers[temp2] -= 1
    else:
        print(numbers[temp2])


from collections import defaultdict
def solve():
    numbers = defaultdict(int)
    for i in range(int(input())):
        operation, operator = input().split()
        operator = ''.join(['1' if char in ['1', '3', '5', '7', '9'] else '0' for char in operator]).zfill(18)

        if operation == '+':
            numbers[operator] += 1
        elif operation == '-':
            numbers[operator] -= 1
        else:
            print(numbers[operator])

solve()


n = int(input())
D = {}

def get_hash(x):
    return ("".join(['1' if xi in ('1', '3', '5', '7', '9') else '0' for xi in x])).zfill(18)

def get_match(x):
    x = x.zfill(18)
    return D.get(x, 0)

for i in range(n):
    c, a = input().split()
    p = get_hash(a)
    if c == '+':
        D.setdefault(p, 0)
        D[p] += 1
    elif c == '-':
        D.setdefault(p, 0)
        D[p] -= 1
    elif c == '?':
        print(get_match(a))


import sys
n = int(input())
D = {}
c = 5

def get_hash(x):
    return ("".join(['1' if xi in ('1', '3', '5', '7', '9') else '0' for xi in x])).zfill(18)

def get_match(x):
    x = x.zfill(18)
    return D.get(x, 0)

for i in range(n):
    c, a = input().split()
    p = get_hash(a)
    if c == '+':
        D.setdefault(p, 0)
        D[p] += 1
    elif c == '-':
        D.setdefault(p, 0)
        D[p] -= 1
    elif c == '?':
        print(get_match(a))
    else:
        sys.exit(0)


from collections import defaultdict
import sys

numbers = defaultdict(int)
sys.stdin.readline()
output = ''
for line in sys.stdin:
    operation, operator = line.split()
    operator = ''.join(['1' if char in ['1', '3', '5', '7', '9'] else '0' for char in operator]).zfill(18)

    if operation == '+':
        numbers[operator] += 1
    elif operation == '-':
        numbers[operator] -= 1
    else:
        output += '{}\n'.format(numbers[operator])

print(output)


from collections import defaultdict

numbers = defaultdict(int)
for i in range(int(input())):
    operation, operator = eval(input()).split()
    operator = ''.join(['1' if char in ['1', '3', '5', '7', '9'] else '0' for char in operator]).zfill(18)

    if operation == '+':
        numbers[operator] += 1
    elif operation == '-':
        numbers[operator] -= 1
    else:
        print(numbers[operator])


from collections import defaultdict

numbers = defaultdict(int)
for i in range(int(input())):
    operation, operator = input().split()
    operator = ''.join([str(int(char) & 1) for char in operator]).zfill(18)

    if operation == '+':
        numbers[operator] += 1
    elif operation == '-':
        numbers[operator] -= 1
    else:
        print(numbers[operator])


import sys
from collections import Counter
from sys import stdin

input()
c = [0]*2**18

for ch,n in map(str.split,stdin):
	val = 0
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 1:
			val += 2**(len(n) - i - 1)

	if ch == '?':
		print(c[val])

	if ch == '+':
		c[val] += 1

	if ch == '-':
		c[val] -= 1


import sys
from collections import Counter
from sys import stdin

input()
c = [0]*2**18

for ch,n in map(str.split,stdin):
	n = list(n)
	n.reverse()
	while len(n) < 18:
		n += '0'
	val = 0
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 0:
			val = val * 2
		else:
			val = val * 2 + 1

	if ch == '?':
		print(c[val])

	if ch == '+':
		c[val] += 1

	if ch == '-':
		c[val] -= 1


import sys
from collections import Counter
from sys import stdin

input()
c = [0]*2**18
deg = [0]*18
for i in range(18):
	deg[i] = 2**i

for ch,n in map(str.split,stdin):
	val = 0
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 1:
			val += deg[len(n)-i-1]

	if ch == '?':
		print(c[val])

	if ch == '+':
		c[val] += 1

	if ch == '-':
		c[val] -= 1


import sys
from collections import Counter

t = int(input())
c = Counter()

for i in range(t):
	ch, n = sys.stdin.readline().split()
	n = list(n)
	n.reverse()
	while len(n) < 20:
		n += '0'
	val = 0
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 0:
			val = val * 2
		else:
			val = val * 2 + 1

	if ch == '?':
		print(c[val])

	if ch == '+':
		c[val] += 1

	if ch == '-':
		c[val] -= 1


import sys
from collections import Counter

t = int(input())
c = [0]*1000005

for i in range(t):
	ch, n = sys.stdin.readline().split()
	n = list(n)
	n.reverse()
	while len(n) < 20:
		n += '0'
	val = 0
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 0:
			val = val * 2
		else:
			val = val * 2 + 1

	if ch == '?':
		print(c[val])

	if ch == '+':
		c[val] += 1

	if ch == '-':
		c[val] -= 1


import sys
from collections import Counter

t = int(input())
c = Counter()

for i in range(t):
	ch, n = sys.stdin.readline().split()
	n = list(n)
	n.reverse()
	val = 0
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 0:
			val = val * 2
		else:
			val = val * 2 + 1

	if ch == '?':
		print(c[val])

	if ch == '+':
		c[val] += 1

	if ch == '-':
		c[val] -= 1


import sys
from collections import Counter
from sys import stdin

input()
c = [0]*2**18
deg = [0]*18
for i in range(18):
	deg[i] = 2**i
t=str.maketrans("0123456789","0101010101")
for ch,n in map(str.split,stdin):

	if ch == '?':
		print(c[int(n, 2)])
	n = n.translate(t)
	if ch == '+':
		c[int(n,2)] += 1

	if ch == '-':
		c[int(n,2)] -= 1


import sys
from collections import Counter

t = int(input())
c = Counter()

for i in range(t):
	ch, n = sys.stdin.readline().split()
	n = list(n)
	n.reverse()
	while len(n) < 20:
		n += '0'
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 0:
			n[i]='0'
		else:
			n[i]='1'
	n = str(n)
	if ch == '?':
		print(c[n])

	if ch == '+':
		c[n] += 1

	if ch == '-':
		c[n] -= 1


import sys
from collections import Counter

t = int(input())
c = [0]*2000005

for i in range(t):
	ch, n = sys.stdin.readline().split()
	n = list(n)
	n.reverse()
	while len(n) < 20:
		n += '0'
	val = 0
	for i in range(len(n)):
		if (ord(n[i])-ord('0')) % 2 == 0:
			val = val * 2
		else:
			val = val * 2 + 1

	if ch == '?':
		print(c[val])

	if ch == '+':
		c[val] += 1

	if ch == '-':
		c[val] -= 1


t = int(input())
rules = str.maketrans("0123456789", "0101010101")
trans = lambda x : str.translate(x, rules)
cnt, res = {}, []
for _ in range(t):
    op, n = input().split()
    n = int(trans(n), 2)
    if op == '+':
        cnt[n] = cnt.get(n, 0) + 1
    elif op == '-':
        cnt[n] -= 1
    else:
        res.append(str(cnt.get(n, 0)))
print('\n'.join(res))


import itertools

t = int(input())
a = []
for i in range(t):
    string = input()
    number = string[2:]
    if string[0] == '+':
        a.append(number)
    elif string[0] == '-':
        a.remove(number)
    else:
        count = 0
        for a_i in a:
            b = True
            for i, j in itertools.zip_longest(a_i[::-1], number[::-1], fillvalue='0'):
                if not int(i) % 2 == int(j) % 2:
                    b = False
                    break
            if b:
                count += 1
        print(count)


t = int(input())
trantab = str.maketrans('0123456789', '0101010101')
a = {}
for i in range(t):
    string = input()
    oper, number = string.split()
    pattern = int(number.translate(trantab))
    if oper == '+':
        a[pattern] = a.get(pattern, 0) + 1
    elif oper == '-':
        a[pattern] -= 1
        if not a[pattern]:
            del a[pattern]
    else:
        if pattern in a:
            print(a[pattern])
        else:
            print(0)


t = int(input())
trantab = str.maketrans('0123456789', '0101010101')
a = {}
for i in range(t):
    string = input()
    oper, number = string.split()
    pattern = int(number.translate(trantab))
    if oper == '+':
        a[pattern] = a.get(pattern, 0) + 1
    elif oper == '-':
        a[pattern] -= 1
        if not a[pattern]:
            del a[pattern]
    else:
        if pattern in a:
            print(a[pattern])


t = int(input())
a = []
for i in range(t):
    string = input()
    number = string[2:]
    if string[0] == '+':
        a.append(number)
    elif string[0] == '-':
        a.remove(number)
    else:
        count = 0
        for a_i in a:
            for i, j in zip(a_i[::-1], number[::-1]):
                if not int(i) % 2 == int(j) % 2:
                    break
                count += 1
        print(count)


t = int(input())
trantab = str.maketrans('0123456789', '0101010101')
a = {}
for i in range(t):
    string = input()
    oper = string[0]
    number = string[2:]
    if oper == '+':
        a[number] = a.get(number, 0) + 1
    elif oper == '-':
        a[number] -= 1
    else:
        count = 0
        for a_i in a:
            max_length = max(len(number), len(a_i))
            if a_i.translate(trantab).rjust(max_length, '0') == number.rjust(max_length, '0'):
                count += 1
        print(count)


t = int(input())
trantab = str.maketrans('0123456789', '0101010101')
a = []
for i in range(t):
    string = input()
    oper = string[0]
    number = string[2:]
    if oper == '+':
        a.append(number)
    elif oper == '-':
        a.remove(number)
    else:
        count = 0
        for a_i in a:
            max_length = max(len(number), len(a_i))
            if a_i.translate(trantab).rjust(max_length, '0') == number.rjust(max_length, '0'):
                count += 1
        print(count)


t = int(input())
trantab = str.maketrans('0123456789', '0101010101')
a = {}
for i in range(t):
    string = input()
    oper, number = string.split()
    if oper == '+':
        a[number] = a.get(number, 0) + 1
    elif oper == '-':
        a[number] -= 1
        if not a[number]:
            del a[number]
    else:
        count = 0
        for a_i in a:
            max_length = max(len(number), len(a_i))
            if a_i.translate(trantab).rjust(max_length, '0') == number.rjust(max_length, '0'):
                count += 1
        print(count)


from sys import *

def mask(a):
	res1=''
	while a>0:
		p=(a%10)%2
		res1+=str(p)
		a//=10
	while len(res1)<18:
		res1+='0'
	return res1[::-1]

di=dict()
t=int(stdin.readline())
for i in range(t):
	s=stdin.readline().split()
	if s[0]=='+':
		w=mask(int(s[1]))
		if di.get(w,-1)==-1:
			di[w]=1
		else:
			di[w]+=1
	if s[0]=='-':
		w=mask(int(s[1]))
		di[w]-=1
	if s[0]=='?':
		w=mask(int(s[1]))
		if di.get(w,-1)==-1:
			print('0')
		else:
			print(di[w])


from sys import *

#def mask(a):
#   res1=''
#   while a>0:
#       p=(a%10)%2
#       res1+=str(p)
#       a//=10
#   res1+='0'*(18-len(res1))
#   return res1[::-1]

odd=set(["1","9","3","5","7"])

def mask(a):
    res="0"*(18-len(a))
    for i in a:
        if i in odd:
            res+="1"
        else:
            res+="0"
    return res

di=dict()
t=int(stdin.readline())
for i in range(t):
    s=stdin.readline().split()
    if s[0]=='+':
        w=mask(s[1])
        if di.get(w,-1)==-1:
            di[w]=1
        else:
            di[w]+=1
    if s[0]=='-':
        w=mask(s[1])
        di[w]-=1
    if s[0]=='?':
        w=mask(s[1])
        if di.get(w,-1)==-1:
            print('0')
        else:
            print(di[w])


from sys import *

#def mask(a):
#   res1=''
#   while a>0:
#       p=(a%10)%2
#       res1+=str(p)
#       a//=10
#   res1+='0'*(18-len(res1))
#   return res1[::-1]

odd=set(["1","9","3","5","7"])

def mask(a):
    res="0"*(18-len(a))
    for i in a:
        if i in even:
            res+="1"
        else:
            res+="0"
    return res

di=dict()
t=int(stdin.readline())
for i in range(t):
    s=stdin.readline().split()
    if s[0]=='+':
        w=mask(s[1])
        if di.get(w,-1)==-1:
            di[w]=1
        else:
            di[w]+=1
    if s[0]=='-':
        w=mask(s[1])
        di[w]-=1
    if s[0]=='?':
        w=mask(s[1])
        if di.get(w,-1)==-1:
            print('0')
        else:
            print(di[w])


def main():
	n = int(input())

	d = dict()
	for _ in range(n):
		s, x = input().split()

		a = [0] * 18
		k = int(x)
		i = 0
		while k:
			a[i] = k % 2
			i += 1
			k = k // 10
		a.reverse()
		x = ''.join(str(e) for e in a)

		if s == '+': d[x] = d.get(x, 0) + 1
		elif s == '-': d[x] = d.get(x) - 1
		else: print(d.get(x, 0))

if __name__ == '__main__':
	main()


from collections import defaultdict

def main():
	n = int(input())

	d = defaultdict(int)
	for _ in range(n):
		s, x = input().split()

		a = [0] * 18
		k = int(x)
		i = 0
		while k:
			a[i] = k % 2
			i += 1
			k = k // 10
		a.reverse()
		x = ''.join(str(e) for e in a)

		if s == '+': d[x] += 1
		elif s == '-': d[x] -= 1
		else: print(d[x])

if __name__ == '__main__':
	main()


from collections import defaultdict
from sys import stdin
from sys import stdout

def main():
	n = int(stdin.readline())

	d = defaultdict(int)
	for i in range(n):
		s, x = stdin.readline().split()

		a = [0] * 18
		k = int(x)
		i = 0
		while k:
			a[i] = k % 2
			i += 1
			k = k // 10
		a.reverse()
		x = ''.join(str(e) for e in a)

		if s == '+': d[x] += 1
		elif s == '-': d[x] -= 1
		else: stdout.write(str(d[x]) + '\n')

if __name__ == '__main__':
	main()


def main():
	n = int(input())

	d = dict()
	for _ in range(n):
		s, x = input().split()

		len_x = len(x)
		for i in range(len_x, 18): x = '0' + x

		pattern = ''
		for i in range(18):
			if x[i] != '0' and x[i] != '1':
				if ord(x[i])%2 == 0: pattern += '0'
				else: pattern += '1'
			else:
				pattern += x[i]

		x = pattern
		if s == '+': d[x] = d.get(x, 0) + 1
		elif s == '-': d[x] = d.get(x) - 1
		else: print(d.get(x, 0))

if __name__ == '__main__':
	main()


from collections import defaultdict
from sys import stdin
from sys import stdout

def main():
	n = int(stdin.readline())

	d = defaultdict(int)
	for i in range(n):
		s, x = stdin.readline().split()
		y = ''.join(['1' if c in ['1', '3', '5', '7', '9'] else '0' for c in x]).zfill(18)

		if s == '+': d[y] += 1
		elif s == '-': d[y] -= 1
		else: stdout.write(str(d[y]) + '\n')

if __name__ == '__main__':
	main()


from collections import defaultdict
import sys

def main():
	sys.stdin.readline()

	d = defaultdict(int)
	for line in sys.stdin:
		s, x = line.split()

		a = [0] * 18
		k = int(x)
		i = 0
		while k:
			a[i] = k % 2
			i += 1
			k = k // 10
		a.reverse()
		x = ''.join(str(e) for e in a)

		if s == '+': d[x] += 1
		elif s == '-': d[x] -= 1
		else: print(d[x])

if __name__ == '__main__':
	main()


#!/usr/local/env python3
# -*- encoding: utf-8 -*-
import sys
from copy import copy

def readnlines(f_in):
    n = int(f_in.readline().strip())
    s = set()
    content = f_in.readline().strip()
    for i, line in zip(range(n), content.split(' ')):
        if line.isdigit():
            s.add(int(line))
        else:
            s.add(line)
    return s

def print_args():
    print("Recieved {} arguments = {}.".format(len(sys.argv), sys.argv))

class SmartDict():

    def __init__(self, max_length=19):
        self.d = {}
        self.length = max_length

    def add(self, i):
        i0 = copy(i)
        d0 = self.d
        for j in range(self.length):
            new = int(i0[-1]) % 2 if len(i0) > 0 else 0
            d0.setdefault(new, {})
            d0 = d0[new]
            if len(i0) > 0:
                i0 = i0[:-1]
        d0.setdefault("count", 0)
        d0["count"] += 1
        return self

    def subs(self, i):
        i0 = copy(i)
        d0 = self.d
        for j in range(self.length):
            new = int(i0[-1]) % 2 if len(i0) > 0 else 0
            d0.setdefault(new, {})
            d0 = d0[new]
            if len(i0) > 0:
                i0 = i0[:-1]
        d0["count"] -= 1
        return self

    def count(self, mask):
        d0 = self.d
        for j in range(self.length):
            new = int(mask[-1]) % 2 if len(mask) > 0 else 0
            if new not in d0:
                return 0
            d0 = d0[new]
            if len(mask) > 0:
                mask = mask[:-1]
        return d0["count"]

def solve():
    d = SmartDict()
    n = int(sys.stdin.readline().strip())
    ans = ""
    for line in sys.stdin:
        op, i = line.strip().split(' ')
        if op == '+':
            d.add(i)
            #print(d.d)
        if op == '-':
            d.subs(i)
            #print(d.d)
        if op == '?':
            ans += "{:d}\n".format(d.count(i))
    return ans

if __name__ == "__main__":
   ans = solve()
   print(ans)


#!/usr/local/env python3
# -*- encoding: utf-8 -*-
import sys
from copy import copy

def readnlines(f_in):
    n = int(f_in.readline().strip())
    s = set()
    content = f_in.readline().strip()
    for i, line in zip(range(n), content.split(' ')):
        if line.isdigit():
            s.add(int(line))
        else:
            s.add(line)
    return s

def print_args():
    print("Recieved {} arguments = {}.".format(len(sys.argv), sys.argv))

def intersect(l1, r1, l2, r2):
    left = max(l1, l2)
    right = min(r1, r2)
    return left, right, max(0, right - left + 1)

class SmartDict():

    def __init__(self, max_length=20):
        self.d = {}
        self.length = max_length

    def add(self, i):
        i0 = copy(i)
        d0 = self.d
        for j in range(self.length):
            new = int(i0[-1]) % 2 if len(i0) > 0 else 0
            d0.setdefault(new, {})
            d0 = d0[new]
            if len(i0) > 0:
                i0 = i0[:-1]
        d0.setdefault("count", 0)
        d0["count"] += 1
        return self

    def subs(self, i):
        i0 = copy(i)
        d0 = self.d
        for j in range(self.length):
            new = int(i0[-1]) % 2 if len(i0) > 0 else 0
            d0.setdefault(new, {})
            d0 = d0[new]
            if len(i0) > 0:
                i0 = i0[:-1]
        d0["count"] -= 1
        return self

    def count(self, mask):
        d0 = self.d
        for j in range(self.length):
            new = int(mask[-1]) % 2 if len(mask) > 0 else 0
            if new not in d0:
                return 0
            d0 = d0[new]
            if len(mask) > 0:
                mask = mask[:-1]
        return d0["count"]

def solve():
    d = SmartDict()
    n = int(sys.stdin.readline().strip())
    ans = ""
    for line in sys.stdin:
        op, i = line.strip().split(' ')
        if op == '+':
            d.add(i)
            #print(d.d)
        if op == '-':
            d.subs(i)
            #print(d.d)
        if op == '?':
            ans += "{:d}\n".format(d.count(i))
    return ans

if __name__ == "__main__":
   ans = solve()
   print(ans)


#!/usr/local/env python3
# -*- encoding: utf-8 -*-
import sys
import re

def mask2(s):
    m = int("0", 2)
    while len(s) > 0:
        m *= 2
        m += int(s[0]) % 2
        s = s[1:]
    return m

def mask(s):
    return int(re.sub("[02468]", "0", re.sub("[13579]", "1", s)), 2)

def solve():
    d = dict()
    n = int(sys.stdin.readline().strip())
    ans = ""
    for line in sys.stdin:
        op, i = line.strip().split(' ')
        m = mask(i)
        if op == '+':
            d.setdefault(m, 0)
            d[m] += 1
        if op == '-':
            d[m] -= 1
        if op == '?':
            ans += "{:d}\n".format(d.get(m, 0))
    return ans

if __name__ == "__main__":
   ans = solve()
   print(ans)


#!/usr/local/env python3
# -*- encoding: utf-8 -*-
import sys

def mask(s):
    m = int("0", 2)
    while len(s) > 0:
        m *= 2
        m += int(s[0]) % 2
        s = s[1:]
    return m

def solve():
    d = dict()
    n = int(sys.stdin.readline().strip())
    ans = ""
    for line in sys.stdin:
        op, i = line.strip().split(' ')
        m = mask(i)
        if op == '+':
            d.setdefault(m, 0)
            d[m] += 1
        if op == '-':
            d[m] -= 1
        if op == '?':
            ans += "{:d}\n".format(d.get(m, 0))
    return ans

if __name__ == "__main__":
   ans = solve()
   print(ans)


num = int(input())
multiset = list()

def str2num(n):
    j = ''
    for i in range(len(n)):
        if n[i] in '13579':
            j += '1'
        else:
            j += '0'
    return int(j)

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset.append(str2num(opr[1]))
    elif opr[0] == '-':
        multiset.remove(str2num(opr[1]))
    elif opr[0] == '?':
        print(multiset.count(str2num(opr[1])))
    num -= 1


num = int(input())
multiset = list()

def check(n):
    cnt = 0
    print(multiset, '检查', n)
    for m in multiset:
        flag = 1
        sub = str(abs(m - n))
        for i in range(len(sub)):
            if int(sub[i]) % 2:
                flag = 0
                break
        if i == len(sub) - 1 and flag:
            cnt += 1
    print(cnt)

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset.append(int(opr[1]))
    elif opr[0] == '-':
        multiset.remove(int(opr[1]))
    elif opr[0] == '?':
        check(int(opr[1]))
    num -= 1


num = int(input())
multiset = list()

def str2num(n):
    s = ''
    for i in n:
        s += str(int(i) % 2)
    return int(s)

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset.append(str2num(opr[1]))
    elif opr[0] == '-':
        multiset.remove(str2num(opr[1]))
    elif opr[0] == '?':
        print(multiset.count(str2num(opr[1])))
    num -= 1


num = int(input())
multiset = list()

def check(n):
    cnt = 0
    for i in multiset:
        if n == i:
            cnt += 1
    print(cnt)

def str2num(n):
    j = ''
    for i in range(len(n)):
        if n[i] in '13579':
            j += '1'
        else:
            j += '0'
    return int(j)

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset.append(str2num(opr[1]))
    elif opr[0] == '-':
        multiset.remove(str2num(opr[1]))
    elif opr[0] == '?':
        check(str2num(opr[1]))
    num -= 1


num = int(input())
multiset = list()
t = str.maketrans('0123456789', '0101010101')

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset.append(int(opr[1].translate(t)))
    elif opr[0] == '-':
        multiset.remove(int(opr[1].translate(t)))
    elif opr[0] == '?':
        print(multiset.count(int(opr[1].translate(t))))
    num -= 1


num = int(input())
multiset = list()

def check(n):
    cnt = 0
    for m in multiset:
        flag = 1
        sub = str(abs(m - n))
        for i in range(len(sub)):
            if int(sub[i]) % 2:
                flag = 0
                break
        if i == len(sub) - 1 and flag:
            cnt += 1
    print(cnt)

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset.append(int(opr[1]))
    elif opr[0] == '-':
        multiset.remove(int(opr[1]))
    elif opr[0] == '?':
        check(int(opr[1]))
    num -= 1


num = int(input())
multiset = [0] * 2 ** 18
t = str.maketrans('0123456789', '0101010101')

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset[int(opr[1].translate(t), 2)] += 1
    elif opr[0] == '-':
        multiset[int(opr[1].translate(t), 2)] -= 1
    elif opr[0] == '?':
        print(multiset[int(opr[1], 2)])
    num -= 1


num = int(input())
multiset = list()

def check(n):
    cnt = 0
    for m in multiset:
        flag = 1
        for i in range(min(len(m), len(n))):
            if abs(int(m[-i - 1]) - int(n[-i - 1])) % 2:
                flag = 0
                break
        if flag:
            if len(m) > len(n):
                for i in range(len(m) - len(n)):
                    if int(m[i]) % 2:
                        flag = 0
                        break
            else:
                for i in range(len(n) - len(m)):
                    if int(n[i]) % 2:
                        flag = 0
                        break
        if flag:
            cnt += 1
    print(cnt)

while num:
    opr = input().split()
    if opr[0] == '+':
        multiset.append(opr[1])
    elif opr[0] == '-':
        multiset.remove(opr[1])
    elif opr[0] == '?':
        check(opr[1])
    num -= 1


present = {}
coded = {}
def encode(s):
    a = ""
    for i in range(len(s)):
        if int(s[i])%2==0:
            a+='0'
        else:
            a+='1'
    x=""
    for i in range(18-len(a)):
        x+='0'
    x+=a
    return x

def add(num):
    present[num]=present.get(num,0)+1
    x = encode(num)
    coded[x]=coded.get(x,0)+1
def delete(num):
    present[num]-=1
    x = encode(num)
    coded[x]-=1
def query(num):
    try:
        print(coded[encode(num)])
    except:
        print(0)
t = int(input())

for q in range(t):
    ty,i = input().split()
    if ty=='+':
        add(i)
    if ty=='-':
        delete(i)
    if ty=='?':
        query(i)
    #print(coded,present)


present = {}
coded = {}
cc = {}

def encode(s):
    a = ""
    for i in range(len(s)):
        if int(s[i])%2==0:
            a+='0'
        else:
            a+='1'
    x=""
    for i in range(18-len(a)):
        x+='0'
    x+=a
    return x

def add(num):
    present[num]=present.get(num,0)+1
    x = encode(num)
    cc[num]=x
    coded[x]=coded.get(x,0)+1

def delete(num):
    present[num]-=1
    coded[cc[num]]-=1

def query(patt):
    x = ""
    for i in range(18-len(patt)):
        x+='0'
    x = x+patt

    if x in coded:
        print(coded[x])
    else:
        print(0)

t = int(input())

for q in range(t):
    ty,i = input().split()
    if ty=='+':
        add(i)
    if ty=='-':
        delete(i)
    if ty=='?':
        query(i)
    #print(coded,present)


present = {}
coded = {}
def encode(s):
    a = ""
    for i in range(len(s)):
        if int(s[i])%2==0:
            a+='0'
        else:
            a+='1'
    x=""
    for i in range(18-len(a)):
        x+='0'
    x+=a
    return x

def add(num):
    present[num]=present.get(num,0)+1
    x = encode(num)
    coded[x]=coded.get(x,0)+1
def delete(num):
    present[num]-=1
    x = encode(num)
    coded[x]-=1
def query(num):
    print(coded[encode(num)])

t = int(input())

for q in range(t):
    ty,i = input().split()
    if ty=='+':
        add(i)
    if ty=='-':
        delete(i)
    if ty=='?':
        query(i)
    #print(coded,present)


#				 Author: Udit "luctivud" Gupta @ https://www.linkedin.com/in/udit-gupta-1b7863135/					 #

import math;   		from collections import *
import sys;   		from functools import reduce
import time;   		from itertools import groupby

# sys.setrecursionlimit(10**6)

# def input()         : return sys.stdin.readline()
def get_ints()      : return map(int, input().strip().split())
def get_list()      : return list(get_ints())
def get_string()    : return list(input().strip().split())
def printxsp(*args) : return print(*args, end="")
def printsp(*args)  : return print(*args, end=" ")

DIRECTIONS = [(+0, +1), (+0, -1), (+1, +0), (+1, -1)]
NEIGHBOURS = [(-1, -1), (-1, +0), (-1, +1), (+0, -1),\
              (+1, +1), (+1, +0), (+1, -1), (+0, +1)]

# MAIN >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

# for _test_ in range(int(input())):
n = int(input())
d = defaultdict(int)
oddDig = "13579"
evenDig = "02468"
for __ in range(n):
	a, b = input().split()
	if a in '+-':
		thisPattern = ""
		for i in b:
			if i in evenDig:
				thisPattern += '0'
			else:
				thisPattern += '1'
		thisPattern = thisPattern.rjust(18, '0')
		if a == '+':
			d[thisPattern] += 1
		else:
			d[thisPattern] -= 1
	else:
		b = b.rjust(18, '0')
		print(d[b])
	# print(d)


from sys import stdin
input()
cnt=[0]*2**18
t=str.maketrans("0123456789","0101010101")
for ch,s in map(str.split,stdin):
    if ch=='?' :
        print(cnt[int(s,2)])
    else :
        cnt[int(s.translate(t),2)]+= (1 if ch=='+' else -1 )


from sys import stdin

input()

cnt=[0]*2**18

t=str.maketrans("0123456789","0101010101")

for ch,s in map(str.split,stdin):

    if ch=='?' :

        print(cnt[int(s,2)])

    else :

        cnt[int(s.translate(t),2)]+= (1 if ch=='+' else -1 )

# Made By Mostafa_Khaled


t = int(input())
ans = [0] * 100000
y = str.maketrans('0123456789', '0101010101')

for i in range(t):
    x, s = map(str, input().split())
    if x == '+':
        ans[int(s.translate(y), 2)] += 1
    elif x == '-':
        ans[int(s.translate(y), 2)] -= 1
    else:
        print(ans[int(s.translate(y), 2)])


def sss(a, n):
    if len(a) < len(n):
        a = '0' * (len(n) - len(a)) + a
    elif len(a) > len(n):
        n = '0' * (len(a) - len(n)) + n
    #print(len(a), len(n))
    a = a[::-1]
    n = n[::-1]

    for i in range(len(n)):
        if a[i] == '0' and int(n[i]) % 2 != 0:
            return False
        elif a[i] == '1' and int(n[i]) % 2 == 0:
            return False
    return True

def shablon(s):
    ans = ''
    for i in range(len(s)):
        ans += str(int(s[i]) % 2)
    return ans

t = int(input())
d = dict()
ans = []

for i in range(t):
    s = input()
    if s[0] == '+':
        x = s[2:]
        if x in d:
            d[x][0] += 1
        else:
            d[x] = [1, shablon(x)]

    elif s[0] == '-':
        x = s[2:]
        if d[x][0] > 1:
            d[x][0] -= 1
        else:
            d.pop(x)
    else:
        c = 0
        x = s[2:]
        #print(d)
        for elem in d:
            y = x
            z = d[elem][1]
            if (len(y) < len(z)):
                y = '0' * (len(z) - len(y)) + y
            elif (len(y) > len(z)):
                z = '0' * (len(y) - len(z)) + z

            if z == y:
                #print('elem', elem)
                c += d[elem][0]
        ans.append(c)

print('\n'.join(map(str, ans)))


t = int(input())
ans = [0] * 2 ** 18
y = str.maketrans('0123456789', '0101010101')

for i in range(t):
    x, s = map(str, input().split())
    if x == '+':
        ans[int(s.translate(y), 2)] += 1
    elif x == '-':
        ans[int(s.translate(y), 2)] -= 1
    else:
        print(ans[int(s.translate(y), 2)])


def sss(a, n):
    if len(a) < len(n):
        a = '0' * (len(n) - len(a)) + a
    elif len(a) > len(n):
        n = '0' * (len(a) - len(n)) + n
    #print(len(a), len(n))
    a = a[::-1]
    n = n[::-1]

    for i in range(len(n)):
        if a[i] == '0' and int(n[i]) % 2 != 0:
            return False
        elif a[i] == '1' and int(n[i]) % 2 == 0:
            return False
    return True

t = int(input())
d = dict()

for i in range(t):
    s = input()
    if s[0] == '+':
        x = s[2:]
        if x in d:
            d[x] += 1
        else:
            d[x] = 1

    elif s[0] == '-':
        x = s[2:]
        if d[x] > 1:
            d[x] -= 1
        else:
            d.pop(x)
    else:
        c = 0
        x = s[2:]
        #print(s)
        for elem in d:
            if sss(x, elem):
                #print('elem', elem)
                c += d[elem]
        print(c)


def sss(a, n):
    if len(a) < len(n):
        a = '0' * (len(n) - len(a)) + a
    elif len(a) > len(n):
        n = '0' * (len(a) - len(n)) + n
    #print(len(a), len(n))
    a = a[::-1]
    n = n[::-1]

    for i in range(len(n)):
        if a[i] == '0' and int(n[i]) % 2 != 0:
            return False
        elif a[i] == '1' and int(n[i]) % 2 == 0:
            return False
    return True

t = int(input())
d = dict()
ans = []

for i in range(t):
    s = input()
    if s[0] == '+':
        x = s[2:]
        if x in d:
            d[x] += 1
        else:
            d[x] = 1

    elif s[0] == '-':
        x = s[2:]
        if d[x] > 1:
            d[x] -= 1
        else:
            d.pop(x)
    else:
        c = 0
        x = s[2:]
        #print(s)
        for elem in d:
            if sss(x, elem):
                #print('elem', elem)
                c += d[elem]
        ans.append(c)

print('\n'.join(map(str, ans)))


def s(a, n):
    if len(a) < len(n):
        a = '0' * (len(n) - len(a)) + a
    a = a[::-1]
    n = n[::-1]

    for i in range(len(n)):
        if a[i] == '0' and int(n[i]) % 2 != 0:
            return False
        elif a[i] == '1' and int(n[i]) % 2 == 0:
            return False
    return True

t = int(input())
d = dict()

for i in range(t):
    s = input()
    if s[0] == '+':
        x = int(s[1:])
        if x in d:
            d[x] += 1
        else:
            d[x] = 1

    elif s[0] == '-':
        x = int(s[1:])
        if d[x] > 1:
            d[x] -= 1
        else:
            d.pop(x)
    else:
        c = 0
        for elem in d:
            if s(elem):
                c += d[elem]
        print(c)


n = int(input())
ans = [0] * 2 ** 18
trantab = str.maketrans('0123456789', '0101010101')

for i in range(n):
    ch, s = map(str, input().split())
    if ch == '+':
        ans[int(s.translate(trantab), 2)] += 1
    elif ch == '-':
        ans[int(s.translate(trantab), 2)] -= 1
    else:
        print(s, s.translate(trantab))


n = int(input())
ans = [0] * 2 ** 18
trantab = str.maketrans('0123456789', '0101010101')

for i in range(n):
    ch, s = map(str, input().split())
    if ch == '+':
        ans[int(s.translate(trantab), 2)] += 1
    elif ch == '-':
        ans[int(s.translate(trantab), 2)] -= 1
    else:
        print(ans[int(s.translate(trantab), 2)])


from collections import defaultdict
t = int(input())
d = defaultdict(int)
for i in range(t):
    typ, val = input().split()
    val = "{:0>18}".format(val)
    if typ == "?":
        print(d[val])
    else:
        val = list(val)
        for pos, digit in enumerate(val):
            val[pos] = str(int(digit)%2)
        val = ''.join(val)
        if typ == "+":
            d[val]+=1
        else:
            d[val]-=1


from sys import stdin, stdout
from collections import defaultdict
t = int(input())
d = defaultdict(int)
for line in stdin.readlines():
    typ, val = line.split()
    val = "{:0>18}".format(val)
    if typ == "?":
        stdout.write(str(d[val])+'\n')
    else:
        val = list(val)
        for pos, digit in enumerate(val):
            val[pos] = str(int(digit)%2)
        val = ''.join(val)
        if typ == "+":
            d[val]+=1
        else:
            d[val]-=1


import sys
from collections import defaultdict
t = int(input())
d = defaultdict(int)
for i in range(t):
    typ, val = sys.stdin.readline().split()
    val = "{:0>18}".format(val)
    if typ == "?":
        print(d[val])
    else:
        val = list(val)
        for pos, digit in enumerate(val):
            val[pos] = str(int(digit)%2)
        val = ''.join(val)
        if typ == "+":
            d[val]+=1
        else:
            d[val]-=1


from sys import stdin, stdout
from collections import defaultdict
input()
d = defaultdict(int)
regex = str.maketrans("0123456789","0101010101")
for line in stdin.readlines():
    typ, val = line.split()
    if typ == "?":
        print(d[int(val,2)])
    else:
        val = int(val.translate(regex), 2)
        if typ == "+":
            d[val]+=1
        else:
            d[val]-=1


# Tags: #bits, #bitmask

t = int(input())
dc = [0]*(2**19)
tt = str.maketrans('0123456789', '0101010101')

for i in range(0, t):
    st = input().split()
    if st[0] == '+':
        dc[int(st[1].translate(tt), 2)] += 1
    elif st[0] == '-':
        dc[int(st[1].translate(tt), 2)] -= 1
    else:
        mu = int(st[1], 2)
        print(dc[mu])


# Tags: #bits, #bitmask

t = int(input())
dc = [0]*(2**19)

for i in range(0, t):
    st = input().split()
    if st[0] == '+':
        mu = 0
        for c in st[1]:
            mu *= 2
            if int(c) % 2 != 0:
                mu += 1

        dc[mu] += 1

    elif st[0] == '-':
        mu = 0
        for c in st[1]:
            mu *= 2
            if int(c) % 2 != 0:
                mu += 1

        dc[mu] -= 1
    else:
        mu = int(st[1], 2)
        print(dc[mu])


# Tags: #bits, #bitmask

t = int(input())
dc = dict()

for i in range(0, t):
    st = input().split()
    if st[0] == '+':
        pt = list()
        for c in st[1]:
            if int(c) % 2 == 0:
                pt.append("0")
            else:
                pt.append("1")
        nu = int(''.join(pt), 2)
        if nu not in dc:
            dc[nu] = 0
        dc[nu] += 1
        # print("Count of", nu, "is now", dc[nu])
    elif st[0] == '-':
        pt = list()
        for c in st[1]:
            if int(c) % 2 == 0:
                pt.append("0")
            else:
                pt.append("1")
        nu = int(''.join(pt), 2)
        dc[nu] -= 1
        # print("Count of", nu, "is now", dc[nu])
    else:
        nu = int(st[1], 2)
        # print("Giving you count of", nu, "and it is", dc[nu])
        if nu not in dc:
            dc[nu] = 0
        print(dc[nu])


# Tags: #bits, #bitmask

t = int(input())
dc = dict()

for i in range(0, t):
    st = input().split()
    if st[0] == '+':
        pt = list()
        for c in st[1]:
            if int(c) % 2 == 0:
                pt.append("0")
            else:
                pt.append("1")
        nu = int(''.join(pt), 2)
        if nu not in dc:
            dc[nu] = 0
        dc[nu] += 1
        # print("Count of", nu, "is now", dc[nu])
    elif st[0] == '-':
        pt = list()
        for c in st[1]:
            if int(c) % 2 == 0:
                pt.append("0")
            else:
                pt.append("1")
        nu = int(''.join(pt), 2)
        dc[nu] -= 1
        # print("Count of", nu, "is now", dc[nu])
    else:
        nu = int(st[1], 2)
        # print("Giving you count of", nu, "and it is", dc[nu])
        print(dc[nu])


n = gets.to_i
h = Hash.new(0)
n.times do |i|
  x, num = gets.split(" ")
  a =  num.tr('0-9', '0101010101').to_i
  if x.ord == 43
    h[a] += 1
  elsif x.ord == 45
    h[a] -= 1
  elsif x.ord == 63
    puts h[a]
  end
end


n = gets.to_i
h = Hash.new(0)
n.times do |x|
  c, s = gets.split
  case c
  when '+'
    h[s] += 1
  when '-'
    h[s] -= 1
  when '?'
    a = '^[2|4|6|8|0]*' + s.chars.map{|x| x == '1' ? '[1|3|5|7|9]' : '[2|4|6|8|0]'}.join
    a << '$'
    puts h.keys.select{|x| x.rjust(18, '0').match(Regexp.new(a))}.inject(0){|s, x| s + h[x]}
  end
end


n = gets.to_i
cnt = Array.new(2 ** 18, 0)
n.times do
  c, s = gets.split
  a = s.tr('0-9', '0101010101').to_i(2)
  case c
  when '+'
    cnt[a] += 1
  when '-'
    cnt[a] -= 1
  when '?'
    puts cnt[a]
  end
end


n = gets.to_i
h = Hash.new(0)
a = n.times.map do |i|
  x, s = gets.split
  if x == '+' || x == '-'
    s = s.chars.map do |c|
      c.match(/[1|3|5|7|9]/) ? '1' : '0'
    end.join
  end
  [x, s.rjust(18, '0')]
end
a.each do |x, s|
  if x == '+'
    h[s] += 1
  elsif x == '-'
    h[s] -= 1
  elsif x == '?'
    puts h[s]
  end
end


n = gets.to_i
h = Hash.new(0)
n.times.map do |i|
  x, s = gets.split
  s = s.tr('13579', '1').tr('24680', '1')
  case x
  when '+'
    h[s.rjust(18, '0')] += 1
  when '-'
    h[s.rjust(18, '0')] -= 1
  when '?'
    puts h[s.rjust(18, '0')]
  end
end


n = gets.to_i
h = Hash.new(0)
n.times.map do |i|
  x, s = gets.split
  s = s.tr('13579', '1').tr('24680', '0')
  case x
  when '+'
    h[s.rjust(18, '0')] += 1
  when '-'
    h[s.rjust(18, '0')] -= 1
  when '?'
    puts h[s.rjust(18, '0')]
  end
end


n = gets.to_i
h = Hash.new(0)
n.times do |x|
  c, n = gets.split
  case c
  when '+'
    h[n] += 1
  when '-'
    h[n] -= 1
  when '?'
    a = n.chars.map do |x|
      if x == '1'
        "[1|3|5|7]"
      elsif x == '0'
        "[2|4|6|8|0]"
      end
    end.join
    a << '$'
    puts h.keys.select{|x| x.rjust(5, '0').match(Regexp.new(a))}.inject(0){|s, x| s + h[x]}
  end
end


n = gets.to_i
h = Hash.new(0)
n.times.map do |i|
  x, s = gets.split
  a = s.tr('0-9', '0101010101').to_i
  case x
  when '+'
    h[a] += 1
  when '-'
    h[a] -= 1
  when '?'
    puts h[a]
  end
end


n = gets.to_i
h = Hash.new(0)
n.times do |x|
  c, n = gets.split
  case c
  when '+'
    h[n] += 1
  when '-'
    h[n] -= 1
  when '?'
    a = n.chars.map{|x| x == '1' ? '[1|3|5|7|9]' : '[2|4|6|8|0]'}.join
    a << '$'
    puts h.keys.select{|x| x.rjust(18, '0').match(Regexp.new(a))}.inject(0){|s, x| s + h[x]}
  end
end