#pragma GCC target("avx2")
#pragma GCC optimize("O3")
#pragma GCC optimize("unroll-loops")
#include<iostream>
#include<cstdint>
#include<cstddef>
#include<vector>
//#include<atcoder/all>
//using namespace atcoder;
using namespace std;
using i32 = int_fast32_t;
using i64 = int_fast64_t;
using usize = uint_fast64_t;
#define rep(i, n) for (i64 i = 0; i < (i64)(n); ++i)
#define all(a) (a).begin(),(a).end()
#define rall(a) (a).rbegin(),(a).rend()
using P = pair<i64,i64>;
vector<bool> used;
vector<vector<i64>> g;
vector<i64> a,b;
P ab = {0,0};
void dfs(i64 now){
    used[now] = 1;
    ab.first += a[now];
    ab.second += b[now];
    for(auto v:g[now]){
        if(!used[v])dfs(v);
    }
}
int main(){
    ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    i64 n,m;
    cin >> n >> m;
    g.resize(n);
    a.resize(n);
    b.resize(n);
    used.resize(n);
    rep(i,n){
        cin >> a[i];
    }
    rep(i,n)cin >> b[i];
    rep(i,m){
        i64 c,d;
        cin >> c >> d;
        c--;
        d--;
        g[c].emplace_back(d);
        g[d].emplace_back(c);
    }
    rep(i,n){
        bool flag = 0;
        if(!used[i]){
            dfs(i);
            flag = 1;
        }
        if(flag){
            if(ab.first != ab.second){
                cout << "No" << endl;
                return 0;
            }
            ab = {0,0};
        }
    }
    cout << "Yes" << endl;
}
#include <bits/stdc++.h>
//#include <atcoder/all>
using namespace std;
//using namespace atcoder;

using ll = long long;

#define rep(i, n) for (int i=0; i<(int)(n); ++(i))
#define rep3(i, m, n) for (int i=(m); (i)<(int)(n); ++(i))
#define repr(i, n) for (int i=(int)(n)-1; (i)>=0; --(i))
#define rep3r(i, m, n) for (int i=(int)(n)-1; (i)>=(int)(m); --(i))
#define all(x) (x).begin(), (x).end()

int main() {
	int n;
	string s;
	cin >> n >> s;
	char cl = s.front(), cr = s.back();
	if (cl != cr) cout << 1 << endl;
	else {
		bool ok = false;
		rep3r(i, 2, n-1) {
			if (s[i-1]!=cl && s[i]!=cr) {
				ok = true;
				break;
			}
		}
		if (ok) cout << 2 << endl;
		else cout << -1 << endl;
	}
	return 0;
}
