include <bits/stdc++.h>

#define clr(x) memset((x), 0, sizeof(x))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define in(x) int (x); input((x));
#define x first
#define y second
#define forn(i, n) for(int i = 0; i < (int)(n); ++i)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; --i)
#define for1(i, n) for(int i = 1; i <= (int)(n); ++i)

typedef int itn;

//#define next next12345
//#define prev prev12345
#define left lefdsf232
#define right rig43783
#define x1 x12345
#define y1 y12345

using namespace std;

template<typename T>
T gcd(T x, T y) {
    while (y > 0) {
        x %= y;
        swap(x, y);
    }
    return x;
}

template<class T>
T lcm(T a, T b) {
    return a / gcd(a, b) * b;
}

template<class _T>
inline _T sqr(const _T &x) {
    return x * x;
}

template<class _T>
inline string tostr(const _T &a) {
    ostringstream os("");
    os << a;
    return os.str();
}

typedef long double ld;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const ld PI = 3.1415926535897932384626433832795L;

template<typename T>
inline void input(T &a) {
    static int ed;
    a = 0;
    while (!isdigit(ed = getchar()) && ed != '-') { }
    char neg = 0;
    if (ed == '-') {
        neg = 1;
        ed = getchar();
    }
    while (isdigit(ed)) {
        a = 10 * a + ed - '0';
        ed = getchar();
    }
    if (neg) a = -a;
}

template<typename T = int>
inline T nxt() {
    T res;
    input(res);
    return res;
}

void myassert(bool v) {
    assert(v);
    //cout << "FAIL\n";
    //exit(0);
}

mt19937 generator;

bool check(int v) {
    if (v < 2) return false;
    for (int i = 2; i * i <= v; ++i) {
        if (v % i == 0) {
            return false;
        }
    }
    return true;
}

long long pw(long long a, long long n, long long m) {
    ll res = 1;
    while (n) {
        if (n & 1ll) {
            res = res * a % m;
        }
        a = a * a % m;
        n >>= 1;
    }
    return res;
}

long long inv(long long a, long long p) {
    long long res = 1;
    while (a > 1) {
        res = res * (p - p / a) % p;
        a = p % a;
    }
    return res;
}
vector <int> p;

const int M = 60;

#define ld double

ld dp[1 << 19][M];
ld old[M];
ld old2[M];

void solve(int test) {
    p.resize(1, -1);
    int q = nxt();
    vector <pair <int, int> > r;

    while (q--) {
        int t = nxt();
        int v = nxt() - 1;
        r.pb(mp(t, v));
        if (t == 1) {
            p.pb(v);
        }
    }
    forn(i, M) dp[0][i] = 1;

    int sz = 1;
    for (auto v : r) {
        if (v.x == 1) {
            int cur = sz++;
            forn(i, M) dp[cur][i] = 1;
            int pr = cur;
            cur = p[cur];
            int h = 0;
            while (cur != -1 && h < M) {
                memcpy(old2, dp[cur], sizeof(old2));
                for (int j = h; j < M; ++j) {
                    if (pr != sz - 1) dp[cur][j] /= (0.5 + 0.5 * (j ? old[j - 1] : 0));
                    dp[cur][j] *= (0.5 + 0.5 * (j ? dp[pr][j - 1] : 0));
                }
                memcpy(old, old2, sizeof(old));
                pr = cur;
                cur = p[cur];
                ++h;
            }
        } else {
            ld ans = 0;
            for (int i = 0; i < M; ++i) {
                ans += 1 - dp[v.y][i];
            }
            printf("%.10f\n", (double)ans);
        }
    }
}

int main(int argc, char ** argv) {

#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#else
    #define fname "sequence"
    //freopen(fname".in", "r", stdin);
    //freopen(fname".out", "w", stdout);
#endif
    //ios_base::sync_with_stdio(false);
//    pre();
    int t = 1;

#ifdef LOCAL
#else
#endif
    int c = 0;

    while (t--) {
        solve(++c);
    }

#ifdef LOCAL
    cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << " ms." << endl;
#endif
    return 0;
}


#include <bits/stdc++.h>

#define clr(x) memset((x), 0, sizeof(x))
#define all(x) (x).begin(), (x).end()
#define pb push_back
#define mp make_pair
#define in(x) int (x); input((x));
#define x first
#define y second
#define forn(i, n) for(int i = 0; i < (int)(n); ++i)
#define ford(i, n) for(int i = (int)(n) - 1; i >= 0; --i)
#define for1(i, n) for(int i = 1; i <= (int)(n); ++i)

typedef int itn;

//#define next next12345
//#define prev prev12345
#define left lefdsf232
#define right rig43783
#define x1 x12345
#define y1 y12345

using namespace std;

template<typename T>
T gcd(T x, T y) {
    while (y > 0) {
        x %= y;
        swap(x, y);
    }
    return x;
}

template<class T>
T lcm(T a, T b) {
    return a / gcd(a, b) * b;
}

template<class _T>
inline _T sqr(const _T &x) {
    return x * x;
}

template<class _T>
inline string tostr(const _T &a) {
    ostringstream os("");
    os << a;
    return os.str();
}

typedef long double ld;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const ld PI = 3.1415926535897932384626433832795L;

template<typename T>
inline void input(T &a) {
    static int ed;
    a = 0;
    while (!isdigit(ed = getchar()) && ed != '-') { }
    char neg = 0;
    if (ed == '-') {
        neg = 1;
        ed = getchar();
    }
    while (isdigit(ed)) {
        a = 10 * a + ed - '0';
        ed = getchar();
    }
    if (neg) a = -a;
}

template<typename T = int>
inline T nxt() {
    T res;
    input(res);
    return res;
}

void myassert(bool v) {
    assert(v);
    //cout << "FAIL\n";
    //exit(0);
}

mt19937 generator;

bool check(int v) {
    if (v < 2) return false;
    for (int i = 2; i * i <= v; ++i) {
        if (v % i == 0) {
            return false;
        }
    }
    return true;
}

long long pw(long long a, long long n, long long m) {
    ll res = 1;
    while (n) {
        if (n & 1ll) {
            res = res * a % m;
        }
        a = a * a % m;
        n >>= 1;
    }
    return res;
}

long long inv(long long a, long long p) {
    long long res = 1;
    while (a > 1) {
        res = res * (p - p / a) % p;
        a = p % a;
    }
    return res;
}
vector <int> p;

const int M = 60;

#define ld double

ld dp[1 << 19][M];
ld old[M];
ld old2[M];

void solve(int test) {
    p.resize(1, -1);
    int q = nxt();
    vector <pair <int, int> > r;

    while (q--) {
        int t = nxt();
        int v = nxt() - 1;
        r.pb(mp(t, v));
        if (t == 1) {
            p.pb(v);
        }
    }
    forn(i, M) dp[0][i] = 1;

    int sz = 1;
    for (auto v : r) {
        if (v.x == 1) {
            int cur = sz++;
            forn(i, M) dp[cur][i] = 1;
            int pr = cur;
            cur = p[cur];
            int h = 0;
            while (cur != -1 && h < M) {
                memcpy(old2, dp[cur], sizeof(old2));
                for (int j = h; j < M; ++j) {
                    if (pr != sz - 1) dp[cur][j] /= (0.5 + 0.5 * (j ? old[pr][j - 1] : 0));
                    dp[cur][j] *= (0.5 + 0.5 * (j ? dp[pr][j - 1] : 0));
                }
                memcpy(old, old2, sizeof(old));
                pr = cur;
                cur = p[cur];
                ++h;
            }
        } else {
            ld ans = 0;
            for (int i = 0; i < M; ++i) {
                ans += 1 - dp[v.y][i];
            }
            printf("%.10f\n", (double)ans);
        }
    }
}

int main(int argc, char ** argv) {

#ifdef LOCAL
    freopen("input.txt", "r", stdin);
    freopen("output.txt", "w", stdout);
#else
    #define fname "sequence"
    //freopen(fname".in", "r", stdin);
    //freopen(fname".out", "w", stdout);
#endif
    //ios_base::sync_with_stdio(false);
//    pre();
    int t = 1;

#ifdef LOCAL
#else
#endif
    int c = 0;

    while (t--) {
        solve(++c);
    }

#ifdef LOCAL
    cerr << "Time elapsed: " << 1.0 * clock() / CLOCKS_PER_SEC * 1000 << " ms." << endl;
#endif
    return 0;
}


#include <bits/stdc++.h>

const int N = 2e5 + 5;
struct DP {
	int sum, mx;
	DP operator + (const DP &rhs) const {
		return DP {sum + rhs.sum, std::max (mx, rhs.mx)};
	}
};
inline DP join(DP &a, DP &b) {
  DP c;
  c.sum = a.sum + b.sum;
  c.mx = std::max(a.mx, b.mx);
  return c;
}
int a[N], total[N], down[N], dp[N];
bool good[N];
std::vector<int> edge[N];
int n, k;

void DFS(int u, int fa)	{
	total[u] = 1;
	int sum = 0, mx = 0;
	for (auto v: edge[u])	{
		if (v == fa)	continue;
		DFS (v, u);
		total[u] += total[v];
		if (down[v] == total[v]) {
			sum += total[v];
		} else {
			mx = std::max (mx, down[v]);
		}
	}
	down[u] = sum + mx + 1;
	if (!good[u])	down[u] = 0;
}

void DFS2(int u, int fa, int up)	{
	std::vector<int> children;
	int sum = 0, mx = 0;
	for (auto v: edge[u])	{
		if (v == fa)	continue;
		if (down[v] == total[v]) {
			sum += down[v];
		} else {
			mx = std::max (mx, down[v]);
		}
		children.push_back (v);
	}
	if (up == n - total[u]) {
		sum += up;
	} else {
		mx = std::max (mx, up);
	}
	dp[u] = sum + mx + 1;
	if (!good[u])	dp[u] = 0;

	int sz = children.size ();
	if (sz == 0)	return ;
	std::vector<DP> predown (sz + 1);
	predown[0] = {0, 0};
	for (int i=0; i<sz; ++i)	{
		int v = children[i];
		predown[i+1] = predown[i];
		if (down[v] == total[v]) {
			predown[i+1].sum += down[v];
		} else {
			predown[i+1].mx = std::max (predown[i+1].mx, down[v]);
		}
	}
	std::vector<DP> sufdown (sz + 1);
	sufdown[sz] = {0, 0};
	for (int i=sz-1; i>=0; --i)	{
		int v = children[i];
		sufdown[i] = sufdown[i+1];
		if (down[v] == total[v]) {
			sufdown[i].sum += down[v];
		} else {
			sufdown[i].mx = std::max (sufdown[i].mx, down[v]);
		}
	}
	for (int i=0; i<sz; ++i) {
		int v = children[i];
		//DP now = predown[i] + sufdown[i+1];
		DP now = join (predown[i], sufdown[i+1]);
		if (up == n - total[u]) {
			now.sum += up;
		} else {
			now.mx = std::max (now.mx, up);
		}
		int new_up = now.sum + now.mx + 1;
		if (!good[v]) new_up = 0;
		DFS2 (v, u, new_up);
	}
}

bool check(int v)	{
	DFS (1, 0);
	DFS2 (1, 0, 0);
	for (int i=1; i<=n; ++i)	{
		if (dp[i] >= k)	return true;
	}
	return false;
}

int main()	{
	scanf ("%d%d", &n, &k);
	for (int i=1; i<=n; ++i)	{
		scanf ("%d", a+i);
	}
	for (int u, v, i=1; i<n; ++i)	{
		scanf ("%d%d", &u, &v);
		edge[u].push_back (v);
		edge[v].push_back (u);
	}
	int low = 0, high = 1000005;
	while (low < high)	{
		int mid = (low + high + 1) >> 1;
		//debug
		//printf ("low: %d mid: %d high: %d\n", low, mid, high);
		for (int i=1; i<=n; ++i)	good[i] = (a[i] >= mid);
		if (check (mid))	{
			low = mid;
		} else {
			high = mid - 1;
		}
	}
	printf ("%d\n", low);

	return 0;
}


#include <functional>
#include <algorithm>
#include <iostream>
#include <memory.h>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <assert.h>
#include <bitset>
#include <string>
#include <cstdio>
#include <math.h>
#include <complex>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <ctime>
#include <set>
#include <bitset>
#include <map>
using namespace std;

const int N = 200001;

int n, k;
vector < int > G[N];
int a[N];
int dp1[N], dp2[N];
int sum[N];
int cnt[N];
pair < int, int > pr[N];

void dfs1(int v, int p, int x)
{
	cnt[v] = 1;
	pr[v] = make_pair(-1, -1);
	for (int i = 0; i < G[v].size(); ++i)
	{
		int to = G[v][i];
		if (to == p)
			continue;
		dfs1(to, v, x);
		cnt[v] += cnt[to];
		if (cnt[to] == dp1[to])
			dp1[v] += dp1[to];
		else
		{
			if (pr[v].first == -1 || dp1[pr[v].first] < dp1[to])
			{
				pr[v].second = pr[v].first;
				pr[v].first = to;
			}
			else if (pr[v].second == -1 || dp1[pr[v].second] < dp1[to])
				pr[v].second = to;
		}
	}
	if (a[v] < x)
		dp1[v] = sum[v] = 0;
	else
	{
		sum[v] = dp1[v];
		dp1[v] += 1;
		if (pr[v].first != -1)
			dp1[v] += dp1[pr[v].first];
	}
}

void dfs2(int v, int p, int x)
{
	if (p == -1 || a[p] < x)
	{
		dp2[v] = 0;
	}
	else
	{
		int c = sum[p];
		int mx = 0;
		if (pr[p].first != -1 && pr[p].first != v)
			mx = dp1[pr[p].first];
		else if (pr[p].second != -1 && pr[p].second != v)
			mx = dp1[pr[p].second];
		if (dp1[v] == cnt[v])
			c -= dp1[v];
		dp2[v] = c;
		if (dp2[p] == n - cnt[p])
			dp2[v] += dp2[p];
		else
			mx = max(mx, dp2[p]);
		dp2[v] += mx;
	}
	for (int i = 0; i < G[v].size(); ++i)
	{
		int to = G[v][i];
		if (to == p)
			continue;
		dfs2(to, v, x);
	}
}

bool check(int x)
{
	for (int i = 0; i < n; ++i)
		dp1[i] = dp2[i] = sum[i] = 0;
	dfs1(0, -1, x);
	dfs2(0, -1, x);
	for (int i = 0; i < n; ++i)
	{
		if (a[i] < x)
			continue;
		int ans = sum[i] + 1;
		int mx = 0;
		if (pr[i].first != -1)
			mx = dp1[pr[i].first];
		if (dp2[i] == n - cnt[i])
			ans += dp2[i];
		else
			mx = max(mx, dp2[i]);
		if (ans + mx >= k)
			return true;
	}
	return false;
}
int main()
{
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	scanf("%d%d", &n, &k);
	for (int i = 0; i < n; ++i)
		scanf("%d", &a[i]);
	for (int i = 1; i < n; ++i)
	{
		int u, v; scanf("%d%d", &u, &v); u--; v--;
		G[u].push_back(v);
		G[v].push_back(u);
	}
	int l = 0, r = 1000001;
	while (l + 1 < r)
	{
		int mid = (l + r) / 2;
		if (check(mid))
			l = mid;
		else
			r = mid;
	}
	printf("%d\n", l);
    return 0;
}


#include <bits/stdc++.h>
using namespace std;
const int N = 2e5+5;
int n,sz[N],a[N],c,ret,dp[N];
pair<int,int> m[N][2];
vector<int> adj[N];
void dfs(int x,int p){
	int f=0,u,i,d;dp[x]=0;
	if(!sz[x])f=1,++sz[x];
	d= a[x]>=c ? 1 :0;
	for(i=0;i<adj[x].size();++i){
		u= adj[x][i];
		if(u!=p){
			dfs(u,x);
			if(f)sz[x]+=sz[u];
			if(dp[u]==sz[u])dp[x]+=dp[u];
			else{
				if(m[x][0].first<=dp[u])
					m[x][1]= m[x][0],m[x][0]=make_pair(dp[u],u);
				else if(m[x][1].first<dp[u])
					m[x][1]= make_pair(dp[u],u);
			}
		}
	}
	dp[x]+=d;
	if(d==0)dp[x]=0;
}
int ar[3];
void dfs2(int x,int p,int d){
	int t=d,u,i,v=0,nd,test,z;
	test= dp[x]+ m[x][0].first;
	if(a[x]>=c){
		if(d==n-sz[x])t=0,v=d,test= dp[x]+d;
		else
			test= dp[x]+ max(d,m[x][0].first);
		ar[0]= m[x][0].first,ar[1]= m[x][1].first,ar[2]= t;
		sort(ar,ar+3);
		ret= max(ret,dp[x]+ ar[2]+ar[1]+v);
	}
	for(i=0;i<adj[x].size();++i){
		u= adj[x][i];
		if(u!=p){
			nd=0;z=0;
			if(a[x]>=c){
				nd= dp[x]+v+ max(t,m[x][0].first);
				z= test;
				if(sz[u]==dp[u]){
					nd= dp[x]-sz[u]+ max(m[x][0].first,t)+ v;
					z= test-sz[u];
				}
				else if(u==m[x][0].second){
					nd= dp[x] + v + max(m[x][1].first,t);
					if(d==n-sz[x])z= test-m[x][0].first+m[x][1].first;
					else
						z= dp[x]+max(d,m[x][1].first);
				}
			}
			assert(z==nd);
			dfs2(u,x,nd);
		}
	}
}
int main(){
	int i,x,y,q,l,r,k,mid;
	cin>>n>>k;
	for(i=1;i<=n;++i)scanf("%d",&a[i]);
	for(i=0;i<n-1;++i)scanf("%d%d",&x,&y),adj[x].push_back(y),adj[y].push_back(x);
	dfs(1,0);
	l=1,r= 1e6;
	while(l<r){
		mid= (l+r+1)/2;
		c= mid;
		memset(m,0,sizeof(m));ret=0;
		dfs(1,0);
		dfs2(1,0,0);
		if(ret>=k)l= mid;
		else
			r= mid-1;
	}
	printf("%d\n",l);
}


#include <iostream>
#include <stack>
#include <math.h>
#include <set>
#include <stdio.h>
#include <algorithm>
#include <assert.h>
#include <map>
#include <queue>
#include <utility>
#include <vector>
using namespace std;
#define endl "\n"
#define mp make_pair
#define int long long
#define pii pair<int , int>
inline int in(){int32_t x ; scanf("%d",&x) ; return x ;}
inline string getStr(){char ch[500001] ; scanf("%s",ch) ;return ch;}
const int MAX_N = 2e5 + 10;
inline int gcd( int a, int b ) { return b == 0 ? a : gcd( b, a%b ); }
vector<int> g[MAX_N];
bool del[MAX_N] , forb[MAX_N] , mark[MAX_N];
int a[MAX_N] , dp[MAX_N] ,  ln , vl[MAX_N] , deg[MAX_N];
queue<int> Bomb ; int  n , k;
inline void BombProcess()
{
    for (int i = 1 ; i <= n ; i ++) if (deg[i] == 1 && !forb[i]) Bomb.push(i);
    while (Bomb.size()){
        int first = Bomb.front(); Bomb.pop();
        deg[first] --;
        del[first] = true;
        int FIND = -1;
        for (auto u : g[first]){
            if (!del[u] && !forb[u]){
                FIND = u;
                break;
            }
        }
        if (FIND != -1){
            vl[FIND] += vl[first];
            deg[FIND] --;
            if (deg[FIND] == 1)
                Bomb.push(FIND);
        }
        ln = max(ln , vl[first]);
        vl[first] = 0;
    }
}
int cnt2 = 0 , cnt = 0;
inline void dfs(int v , int pr){

    mark[v] = true;
    dp[v] = vl[v];
    int f1 = 0 , f2 = 0 ;
    for (auto u : g[v]){
        if (!forb[u] && (u - pr)){
            dfs(u , v);
            if (dp[u] > f1){
                f2 = f1;
                f1 = dp[u];
            }
            else{
                f2 = max(f2 , dp[u]);
            }
        }
    }
    if (f2 && f1) cnt2 ++ ;
    if (pr == -1 && f2 && f1) cnt ++;

    ln = max(ln , dp[v] + f2 + f1);
    dp[v] += f1;
}
inline bool can(int low){
    ln = 0;
    for (int i = 1 ; i <= n ; i ++){
        mark[i] = 0;
        deg[i] = g[i].size();
        dp[i] = 0;
        del[i] = 0  ;
        mark[i] = 0 ;
        vl[i] = 1;
        forb[i] = (a[i] < low);
    }
    BombProcess();
    for (int i = 1 ; i <= n ; i ++)if (!mark[i] && !forb[i]) dfs(i , -1) ;
    assert(cnt == cnt2);
    return ln >= k;
}
int32_t main()
{
    n = in() , k = in();
    for (int i = 0 ; i < n ;  i ++) a[i + 1] = in();
    for (int i = 0 ; i < n - 1 ; i ++){
        int v = in() , u = in();
        g[v].push_back(u);
        g[u].push_back(v);

    }
    int l = 0 , r = (1 << 20) , best = 0 , mid;
    while (l <= r){
        mid = (l + r) >> 1;
        if (can(mid)) {best = mid ; l = mid + 1 ; continue ; }
        r = mid - 1;
    }
    cout << best << "\n";
}


#include <iostream>
#include <cstdio>
#include <vector>
#include <stack>
#include <queue>
#include <memory.h>
#include <cmath>
#include <math.h>
#include <set>
#include <cstdlib>
using namespace std;
const int N = 200010;
int n, m, arr[N], tmp , arr2[N] , arr3[N];
vector< int > ans;
int idx1, idx2, idx3;
bool check(int x) {
	if (x > m) {
		idx1 = upper_bound(arr, arr + n, x - m) - arr;
		idx2 = n - 1;
	}
	else {
		idx1 = 0;
		idx2 = upper_bound(arr, arr + n, x) - arr - 1;
	}
	if (idx1 > idx2) {
		return false;
	}
	while (idx2 >= idx1) {
		if (arr[idx1++] + arr[idx2--] != x) {
			return true;
		}
	}
	return false;
}

int main() {
	//freopen("in.txt", "r", stdin);
	//freopen("out.txt", "w", stdout);
	scanf("%d%d", &n, &m);
	for (int i = 0;i < n;i++) {
		scanf("%d", &arr[i]);
		arr2[i] = (arr[i] + arr[0]) % m;
	}
	for (int i = 1;i < n;i++) {
		arr3[i] = arr[i] - arr[i - 1];
	}
	for (int i = 0;i < n;i++) {
		if (!check(arr2[i]) && !check(arr2[i] + m))
			ans.push_back(arr2[i]);
	}
	printf("%d\n", (int)ans.size());
	for (int i = 0;i < (int)ans.size();i++) {
		if (i) putchar(' ');
		printf("%d", ans[i]);
	}
	puts("");
	return 0;
}


/*#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <iomanip>
#include <stack>
#include <queue>
#include <string>
#include <cmath>
#include <map>
#include <cstdlib>
#include <deque>

using namespace std;

#define INF 1000000000
#define MOD 1000000007
#define pb push_back
#define f first
#define s second
#define mp make_pair
#define pii pair <int, int>

const long long MAXN = 1e2 + 10;
//const long double eps = 0.00000000000000001;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector <int> vi;

int l, r;
bool was[MAXN];

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("rbtrees.in", "r", stdin);
    //freopen("rbtrees.out", "w", stdout);
    //cin >> l >> r;
    set <int> st;
    for(int i = 1; i <= MAXN; i++)
        st.insert(i);
    for(int i = 2; i < MAXN + 1; i++){
        if(st.size() < i)
            break;
        //vi v;
        int k = 0;
        for(auto j = st.begin(); j != st.end(); j++){
            k++;
            if(k == i){
                st.erase(*j);
                //if(i == 2)
                  //  cerr << *j << ' ';
                //j--;
                //if(j == st.end())
                  //  break;
                // v.pb(*j);
                k = 0;
            }
        }
        /*for(int j = 0; j < v.size(); j++){
            st.erase(v[j]);
        }*/
    //}
   /* cout << st.size() << endl;
    for(auto j = st.begin(); j != st.end(); j++)
        cout << *j << '\n';

    return 0;
}*/

#include <iostream>
#include <vector>
#include <algorithm>
#include <set>
#include <iomanip>
#include <stack>
#include <queue>
#include <string>
#include <cmath>
#include <map>
#include <cstdlib>
#include <unordered_set>
#include <bitset>

using namespace std;

#define INF 1000000010
#define MOD 1000000007
#define pb push_back
#define f first
#define s second
#define mp make_pair
#define pii pair <int, int>

const long long MAXN = 1000 * 1000 + 10;
const long long pr = 13;

typedef long long ll;
typedef unsigned long long ull;
typedef long double ld;
typedef vector <ll> vi;

ll n, m, a[MAXN];
ll h1[MAXN], h2[MAXN];
vi ans;

ll pw(ll x){
    if(x == 0)
        return 1;
    ll y = pw(x / 2);
    y = y * y % MOD;
    if(x % 2)
        y = y * 13 % MOD;
    return y;
}

void gen(){
    h1[0] = pw(a[0]);
    for(int i = 1; i < n; i++)
        h1[i] = (h1[i - 1] + pw(a[i])) % MOD;
    h2[n - 1] = pw(m - 1 - a[n - 1]);
    for(int i = n - 2; i >= 0; i--)
        h2[i] = (h2[i + 1] + pw(m - 1 - a[i])) % MOD;
  /*  for(int i = 0; i < n; i++)
        cout << h1[i] << ' ';
    cout << '\n';*/
   // for(int i = n - 1; i >= 0; i--)
}

bool check(int i, int j){
    ll x, y;
    x = h1[j];
    y = h2[i];
   // cerr << x << ' ' << y << endl;
    i > 0 ? x = (((h1[j] - h1[i - 1] + MOD) % MOD) * pw(m - a[j])) % MOD : x = (h1[j] * pw(m - a[j])) % MOD;
    j != n - 1 ? y = (((h2[i] - h2[j + 1] + MOD) % MOD) * pw(a[i] + 1)) % MOD : y = (h2[i] * pw(a[i] + 1)) % MOD;
    //cerr << x << ' ' << y << endl;
    return x == y;
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    //freopen("anagrams2.in", "r", stdin);
    //freopen("anagrams2.out", "w", stdout);
    cin >> n >> m;
    for(int i = 0; i < n; i++)
        cin >> a[i];
    if(n == 1){
        if(a[0] == 0 || a[0] == m - 1)
            cout << 1 << '\n' << a[0];
        else
            cout << 0;
        return 0;
    }
    gen();
   // cerr << check(1, 1);
    if(check(0, n - 1) && a[0] - 1 >= m - a[n - 1] - 1){
        //cerr << "aaa";
        ans.pb(a[0] - (m - a[n - 1] - 1) - 1);
    }
    for(int i = 0; i < n - 1; i++){
        if(check(0, i) && check(i + 1, n - 1) && a[i + 1] - a[i] - 1 == a[0] + m - a[n - 1] - 1)
            ans.pb(a[i] + a[0]);
    }
    if(check(0, n - 1) && m - a[n - 1] - 2 >= a[0])
        ans.pb(a[n - 1] + a[0]);
    cout << ans.size() << '\n';
    for(int i = 0; i < ans.size(); i++)
        cout << ans[i] << ' ';
    return 0;
}


#include <cstdio>
#include <algorithm>
#include <vector>

constexpr int MOD = 1000000007;
constexpr int BASE = 7;

using namespace std;
using ll = long long;

int n, m;

int mod_pow(int b, int e) {
    if (e == 0) return 1;
    ll x = mod_pow(b, e >> 1);
    x = (x * x) % MOD;
    if (e & 1) x = (x * b) % MOD;
    return (int) x;
}

vector<pair<int, int>> pre_hash(vector<int> &sparse) {
    vector<pair<int, int>> ans;
    int last = 0;
    ll h = 0;
    for (int idx : sparse) {
        h = (h * mod_pow(BASE, idx - last) + 1) % MOD;
        ans.push_back({ idx, (int) h });
        // printf("pre_hash[%d] = { %d, %d }\n", ans.size() - 1, idx, (int) h);
        last = idx;
    }

    return ans;
}

int eval_hash(const vector<pair<int, int>> &h, int idx) {
    if (h[0].first > idx) return 0;
    // [0, idx]
    int lo = 0, hi = (int) h.size();
    while (lo + 1 < hi) {
        int mid = (lo + hi) / 2;
        if (h[mid].first <= idx) {
            lo = mid;
        } else {
            hi = mid;
        }
    }

    return (1LL * h[lo].second * mod_pow(BASE, idx - h[lo].first)) % MOD;
}

int eval_hash(const vector<pair<int, int>> &h, int l, int r) {
    // [l, r]
    int right_hash = eval_hash(h, r);
    // printf("  got right hash = %d\n", right_hash);
    int left_hash = l == 0 ? 0 : eval_hash(h, l - 1);
    // printf("  got left hash = %d\n", left_hash);
    left_hash = (left_hash * mod_pow(BASE, r - l + 1)) % MOD;
    // printf("  scaled left hash = %d\n", left_hash);
    return (right_hash - left_hash + MOD) % MOD;
}

int main() {
    scanf(" %d %d", &n, &m);
    vector<int> bag;
    for (int i = 0; i < n; ++i) {
        int x;
        scanf(" %d", &x);
        bag.push_back(x);
    }

    sort(bag.begin(), bag.end());

    vector<int> flipped;

    for (int x : bag) {
        flipped.push_back(m - 1 - x);
        flipped.push_back(m + m - 1 - x);
    }

    sort(flipped.begin(), flipped.end());

    // printf("flipped: ");
    // for (int x : flipped) printf("%d ", x);
    // printf("\n");

    vector<int> checks;

    for (int x : flipped) {
        if (x - bag[0] >= 0 && x - bag[0] < m) checks.push_back(x - bag[0]);
    }

    // printf("checks: ");
    // for (int x : checks) printf("%d ", x);
    // printf("\n");

    // printf("hashing bag\n");
    auto bag_h = pre_hash(bag);
    // printf("hashing flipped\n");
    auto flipped_h = pre_hash(flipped);

    int desired_length = m - 1;
    int desired_hash = eval_hash(bag_h, desired_length);

    // printf("desired hash = %d\n", desired_hash);

    vector<int> ans;

    for (int check : checks) {
        int cur_hash = eval_hash(flipped_h, check, check + desired_length);
        // printf("on check %d, got hash %d\n", check, cur_hash);
        if (cur_hash == desired_hash) {
            ans.push_back((m + m - 1 - check) % m);
        }
    }

    sort(ans.begin(), ans.end());

    printf("%d\n", (int) ans.size());
    for (int x : ans) {
        printf("%d ", x);
    }
    printf("\n");

    return 0;
}


#include <cstdio>
#include <set>
#include <vector>
#include <iostream>
#include <algorithm>

using namespace std;

typedef long long LL;

const int maxn = 200005;

LL aa[maxn];
LL jg[maxn];
vector<LL> ans;
set<LL> sxd;

int main()
{
	int n;
	LL m;
	scanf("%d%lld", &n, &m);
	for(int i = 1; i <= n; ++i)
	{
		scanf("%lld", &aa[i]);
		sxd.insert(aa[i]);
	}
	sort(aa + 1, aa + n + 1);
	for(int i = 2; i <= n; ++i)
		jg[i] = aa[i] - aa[i-1] - 1 + jg[i-1];
	LL now = (aa[1] << 1) % m;
	bool f = true;
	for(int i = 2; i <= n; ++i)
	{
		if((aa[i] << 1) % m != now)
		{
			f = false;
			break;
		}
	}
	if(f)
		ans.push_back(now);
	if(!(n & 1))
	{
		f = true;
		int L = 1, R = (n >> 1) + 1;
		now = (aa[L] + aa[R]) % m;
		for(; R != 1; L++, R++, L %= n, R %= n)
		{
			if((aa[L] + aa[R]) % m != now)
			{
				f = false;
				break;
			}
		}
		if(f)
			ans.push_back(now);
	}
	else
	{
		for(int K = 1; K <= n; ++K)
		{
			f = true;
			int L = 1, R = (n >> 1) + 1;
			if(K <= R)
				++R;
			if(K <= L)
				++L;
			now = aa[K] << 1;
			for(; R != 1; L++, R++, L %= n, R %= n)
			{
				if(L == K)
					++L, L %= n;
				if(R == K)
					++R, R %= n;
				if((aa[L] + aa[R]) % m != now)
				{
					f = false;
					break;
				}
			}
			if(f)
				ans.push_back(now);
		}
	}
	if(!((m - n) & 1))
	{
		f = true;
		int RK = (n >> 1) + 1;
		int pla = lower_bound(jg + 1, jg + n + 1, RK) - jg;
		LL nn = aa[pla] + 1 + RK - jg[pla];
		for(int i = 1; i <= n; ++i)
		{
			if(!sxd.count((nn - aa[i] + m) % m))
			{
				f = false;
				break;
			}
		}
		if(f)
			ans.push_back(now);
	}
	sort(ans.begin(), ans.end());
	ans.erase(unique(ans.begin(), ans.end()), ans.end());
	cout << ans.size() << endl;
	for(unsigned i = 0; i < ans.size(); ++i)
		cout << ans[i] << ' ';
	return 0;
}///


#include<iostream>
#include<cstring>
#include<map>
#include<assert.h>
#include<queue>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<vector>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
typedef vector<int> VI;
typedef long long ll;
typedef pair<int,int> PII;
typedef double db;
mt19937 mrand(random_device{}());
const ll mod=1000000007;
const ll mod2=998244353;
int rnd(int x) { return mrand() % x;}
ll powmod(ll a,ll b) {ll res=1;a%=mod; assert(b>=0); for(;b;b>>=1){if(b&1)res=res*a%mod;a=a*a%mod;}return res;}
ll gcd(ll a,ll b) { return b?gcd(b,a%b):a;}

VI pos[10];
int cnt;
ll pw[15],s[15];
ll cnt2,n;
int ans;
int query(int fixpre,ll val) {
	ll ans=0;
	rep(d,0,7) {
		ll offset=(val-fixpre*pw[d])%mod2;
		if (offset<0) offset+=mod2;
		int p=lower_bound(all(pos[d]),mod2-offset)-pos[d].begin();
		ans=(ans+s[d]+offset*SZ(pos[d])-mod2*(SZ(pos[d])-p))%mod;
	}
	return ans;
}

void dfs(int val,int d) {
	int x=(cnt-val+mod2)%mod2;
	pos[d].pb(x); cnt++;
	s[d]+=x;
	if (d==6) return;
	rep(i,0,10) dfs(val*10+i,d+1);
}

void dfs2(ll val) {
	if (val*1000000+999999<=n&&val*10000000>n) {
		ans=(ans+query(val,cnt2+1))%mod;
		cnt2+=cnt;
	} else {
		cnt2++;
		ans=(ans+((cnt2-val)%mod2+mod2)%mod2)%mod;
		rep(i,val?0:1,10) {
			if (val*10+i<=n) dfs2(val*10+i);
		}
	}
}

int main() {
	dfs(0,0);
	rep(i,0,7) sort(all(pos[i]));
	pw[0]=1;
	rep(i,1,13) pw[i]=pw[i-1]*10;
	scanf("%lld",&n);
	cnt2=-1;
	dfs2(0);
	printf("%d\n",ans);
}


#include <bits/stdc++.h>
#define lld long long
using namespace std;
const lld mod1 = 998244353;
const lld mod2 = 1e9 + 7;
lld ans;
lld n;
lld cnt1;
vector < lld > val[7];
lld sum[7];
void dfs1 (lld k1, lld k2) {
	if (k1 == 7) return;
	val[k1].push_back((cnt1 - k2 + mod1) % mod1);
	sum[k1] += (cnt1 - k2 + mod1) % mod1;
	++ cnt1;
	for (lld i = 0; i <= 9; ++ i)
		dfs1 (k1 + 1, k2 * 10 + i);
}
inline bool check(lld x) { return x * 1000000 + 999999 <= n && x * 10000000 > n; }
lld cnt2;
lld poww[7] = { 1, 10, 100, 1000, 10000, 100000, 1000000 };
void dfs2(lld k1, lld k2) {
	if (k2 > n) return;
	if (check(k2)) {
		for (lld i = 0; i <= 6; ++ i) {
			lld offset = ((cnt2 + 1 - (k2 * poww[i])) % mod1 + mod1) % mod1;
			lld pos = lower_bound(val[i].begin(), val[i].end(), mod1 - offset) - val[i].begin();
			ans = (ans + (sum[i] + offset * val[i].size() - mod1 * (val[i].size() - pos))) %= mod2;
		}
		cnt2 += cnt1;
	} else {
		++ cnt2;
		ans = (ans + ((cnt2 - k2) % mod1 + mod1) % mod1) %= mod2;
		for (lld i = (!k1); i <= 9; ++ i)
			dfs2(k1 + 1, k2 * 10 + i);
	}
}
int main() {
	scanf("%lld", & n);
	dfs1 (0, 0);
	for (lld i = 0; i <= 6; ++ i) sort(val[i].begin(), val[i].end());
	cnt2 = -1;
	dfs2 (0, 0);
	printf("%lld\n", ans);
}


#include <bits/stdc++.h>
//#include <ext/pb_ds/assoc_container.hpp>
//#include <ext/pb_ds/hash_policy.hpp>
//#include <ext/pb_ds/priority_queue.hpp>
using namespace std;
//using namespace __gnu_pbds;
#define fi first
#define se second
#define fill0(a) memset(a,0,sizeof(a))
#define fill1(a) memset(a,-1,sizeof(a))
#define fillbig(a) memset(a,63,sizeof(a))
#define pb push_back
#define ppb pop_back
#define mp make_pair
#define mt make_tuple
#define SZ(v) ((int)v.size())
#ifdef LOCAL
#define eprintf(...) fprintf(stderr,__VA_ARGS__)
#else
#define eprintf(...) 1064
#endif
template<typename T1,typename T2> void chkmin(T1 &x,T2 y){if(x>y) x=y;}
template<typename T1,typename T2> void chkmax(T1 &x,T2 y){if(x<y) x=y;}
typedef pair<int,int> pii;
typedef long long ll;
typedef unsigned int u32;
typedef unsigned long long u64;
typedef long double ld;
#ifdef FASTIO
#define FILE_SIZE 1<<23
char rbuf[FILE_SIZE],*p1=rbuf,*p2=rbuf,wbuf[FILE_SIZE],*p3=wbuf;
#ifdef LOCAL
inline char getc(){return getchar();}
inline void putc(char c){putchar(c);}
#else
inline char getc(){return p1==p2&&(p2=(p1=rbuf)+fread(rbuf,1,FILE_SIZE,stdin),p1==p2)?-1:*p1++;}
inline void putc(char x){*p3++=x;}
#endif
template<typename T> void read(T &x){
	x=0;char c=getc();T neg=0;
	while(!isdigit(c)) neg|=(c=='-'),c=getc();
	while(isdigit(c)) x=x*10+(c-'0'),c=getc();
	if(neg) x=-x;
}
template<typename T> void recursive_print(T x){if(!x) return;recursive_print(x/10);putc(x%10^48);}
template<typename T> void print(T x){if(!x) putc('0');if(x<0) putc('-'),x=-x;recursive_print(x);}
template<typename T> void print(T x,char c){print(x);putc(c);}
void readstr(char *s){
	char c=getc();
	while(c<=32||c>=127) c=getc();
	while(c>32&&c<127) s[0]=c,s++,c=getc();
	(*s)=0;
}
void printstr(string s){for(int i=0;i<s.size();i++) putc(s[i]);}
void printstr(char *s){
	int len=strlen(s);
	for(int i=0;i<len; i++) putc(s[i]);
}
void print_final(){fwrite(wbuf,1,p3-wbuf,stdout);}
#endif
const int MOD1=998244353;
const int MOD2=1e9+7;
ll norm(ll x){return (x%MOD1+MOD1)%MOD1;}
ll n,A[20],pw[20],cnt[13][7][1000005];int d[20],len,ans;
int main(){
#ifdef LOCAL
	freopen("in.txt","r",stdin);
	freopen("out.txt","w",stdout);
#endif
	scanf("%lld",&n);for(int i=(pw[0]=1);i<=12;i++)pw[i]=10*pw[i-1];
	ll tmp=n;while(tmp)d[++len]=tmp%10,tmp/=10;reverse(d+1,d+len+1);
	for(int i=1;i<=len;i++)for(int j=1;j<=i;j++)A[i]=A[i]*10+d[j];
	for(int i=1;i<=len;i++){
		ll sum=i;
		for(int j=0;j<i;j++)for(int k=(j==0)?1:0;k<d[j+1];k++)for(int l=j+1;l<=len;l++)sum+=pw[l-j-1];
		// printf("%lld %lld\n",A[i],sum);
		ans=(ans+norm(sum-A[i]))%MOD2;
	}
	for(int i=1;i<=12;i++)for(int j=0;j<=6;j++){
		for(int x=0;x<pw[j];x++){
			static int dd[13];memset(dd,0,sizeof(dd));
			for(int k=1;k<=j;k++)dd[k]=x/pw[j-k]%10;
			for(int k=0;k<j;k++){
				cnt[i][j][x]+=(k>=1);
				for(int l=k+1;l<=i;l++)
					cnt[i][j][x]+=dd[k+1]*pw[i-l];
			}
			// if(i<=2&&j<=2)printf("cnt[%d][%d][%d]=%lld\n",i,j,x,cnt[i][j][x]);
		}
	}
	for(int i=0;i<len;i++)for(int j=(i==0)?1:0;j<10;j++)
		if(j!=d[i+1]){
			int tot=((j<d[i+1])?len:(len-1));
			for(int L=i+1;L<=tot;L++){
				int D=L-i-1,B=D>>1;ll sum=0;
				for(int k=0;k<i;k++){
					sum+=(k!=0);
					for(int d0=(k==0)?1:0;d0<d[k+1];d0++)
						for(int l=k+1;l<=len;l++)sum+=pw[l-k-1];
				}
				if(j<d[i+1]){
					sum+=(i!=0);
					for(int d0=(i==0)?1:0;d0<j;d0++)for(int l=i+1;l<=len;l++)
						sum+=pw[l-i-1];
				}else{
					sum+=(i!=0);
					for(int l=i+1;l<len;l++)sum+=pw[l-i-1];
					sum+=n-A[i+1]*pw[len-i-1]+1;
					for(int d0=(i==0)?1:0;d0<j;d0++)if(d0!=d[i+1])
						for(int l=i+1;l<=((d0<d[i+1])?len:(len-1));l++)
							sum+=pw[l-i-1];
				}
				// printf("%d %d %d %lld\n",i,j,L,sum);
				ll pre=A[i]*10+j;
				if(!D){
					// printf("%lld %lld\n",pre,sum+1);
					ans=(ans+norm(sum+1-pre))%MOD2;continue;
				}
				for(int x=0;x<pw[B];x++)for(int y=0;y<pw[D-B];y++){
					ll V=pre*pw[D]+x*pw[D-B]+y;
					// printf("%lld %lld\n",V,sum+2+(B>0)+cnt[tot-i-1][B][x]+cnt[tot-i-1-B][D-B][y]);
					ans=(ans+norm(sum+2+(B>0)+cnt[tot-i-1][B][x]+cnt[tot-i-1-B][D-B][y]-V))%MOD2;
				}
			}
		}
	printf("%d\n",ans);
	return 0;
}


#if 0
#include <iostream>
#include <cmath>

long long phi( long long n )
{
  long long result = n, nSqrt = sqrt( n );
  for (long long i = 2; i <= nSqrt; ++i)
    if (!(n % i))
    {
      while (!(n % i))
        n /= i;
      result -= result / i;
    }
  if (n > 1)
    result -= result / n;
  return result;
}

int main()
{
  long long n, k, fn;
  std::cin >> n >> k;
  fn = n;
  for (long long i = 1; i <= k && fn != 1; ++i)
    if (i & 1)
      fn = phi(fn);
    else
    {
      /*long long sum = 0, half = fn / 2;
      for (long long j = 1; j <= half && fn != 1; ++j)
        if (!(fn % j))
          sum += phi(j);
      fn = sum + phi(fn);*/
    }
  std::cout << fn % 1000000007;

  return 0;
}
#endif

Skip to content
Search or jump to�

Pull requests
Issues
Marketplace
Explore

@V7074
kanash1
/
tasks - team - 8
1
01
Code
Issues 0
Pull requests 0 Actions
Projects 0
Wiki
Security 0
Insights
tasks - team - 8 / division with remainder / 774E_Big_Number_and_Remainder.cpp
@kanash1 kanash1 Rename 774E_Big_Number_and_Remainder.cpp to division with remainder / 7�
e2b0895 23 hours ago
68 lines( 54 sloc )  2.49 KB

#include <iostream>
#include <string>

using namespace std;

char num[200001];		// �������� �������
int numLen,			// ���������� ���� ��������
m,				// ��������
temp,				// �������
answer = 0;			// ���������� �� ��������
int stepArr = 1;		// �������� �� ������� ������� ����� 10 �� m

int main()
{
	// ���� ������
	cin >> num >> m;

	// ����������� ���������� ���� ��������
	numLen = strlen( num );

	// ���������� ������� ��������� �����
	answer += (num[numLen - 1] - 48) % m;
	for (int i = numLen - 2; i >= 0; i--)
	{
		stepArr = (stepArr * 10) % m;
		answer += ((num[i] - 48) * stepArr) % m;
		answer %= m;
	}

	// ���������� ����������� ������� ����� ������� �����
	/*  =============================================================================
		P - �������� �����
		Q - ����� �����
		m - ��������
			=============================================================================
		����� �������������� ��������� �������:
		P = a_n * 10^n + a_(n-1) * 10^(n-1) + ... + a_0
		Q = a_(n-1) * 10^n + ... + a_0 * 10 + a_n =
			= (a_(n-1) * 10^(n-1) + ... + a_0) * 10 + a_n =
			= (P - a_n * 10^n) * 10 + a_n
			=============================================================================
		�������� �������� ������� �� ������� ��������:
		Q % m = ((P - a_n * 10^n) * 10 + a_n) % m
		Q % m = (((P % m - (a_n % m * 10^n % m) % m + m) % m * 10) % m + a_n % m) % m
		� ������ (P % m - (a_n % m * 10^n % m) % m + m) ���������� m �� ������,
		���� P % m < (a_n % m * 10^n % m) % m
		���� ������� ��������� % m ����� �� ������������
		���������� ������� ������������ ���������� ���� � �����
			============================================================================= */
			// ���������� ����������� ������� ����� ������� �����
	temp = answer;
	for (int i = 0; i < numLen - 1; i++)
	{
		temp = ((((temp - (num[i] - 48) * stepArr) % m + m) * 10) % m + (num[i] - 48) % m) % m;
		if (num[i + 1] ^ 48)
		{
			if (answer > temp)
			{
				answer = temp;
			}
		}
	}
	cout << answer;

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS 1
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <ctime>
#include <queue>
#include <map>
using namespace std;
typedef long long LL;
char num[500005];
int n;
int len;
int mod_num(char num[],int n)
{
	int mod = 0;
	for (int i = 0; i < len; i++)
	{
		mod = (mod * 10 + (num[i] - '0')) % n;
	}
	return mod;
}

void change(int index)
{
	for (int i = 0; i < len; i++)
	{
		temp[i] = (index + i) >= len ? num[index + i - len] : num[index + i];
	}
}
int main()
{
	ios_base::sync_with_stdio(false);
	cin >> num >> n;
	len = strlen(num);
	for (int i = len; i < 2*len; i++)
	{
		num[i] = num[i - len];
	}
	num[2 * len] = '\0';
	int min = 999999999;
	for (int i = 0; i < len; i++)
	{
		if (num[i] != '0')
		{
			//change(i);
			int temp_1 = mod_num(num+i, n);
			if (temp_1 < min)
				min = temp_1;
		}
	}
	cout << min << endl;
	return 0;
}


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

using namespace std;

char cc[500000];

long long m;
long long ans = 99999999;
int main(void)
{
//	freopen("aaa.in","r",stdin);
	scanf("%s",cc);
	int len=0;
	while (cc[len]>='0'&&cc[len]<='9') len++;
	scanf("%I64d",&m);
	int ll=0,xx=m;
	while (xx)
	{
		ll++;
		xx/=10;
		}
//		cout<<ll<<endl;
//	printf("%d",cc[1]);
	for (int i=0;i<len;i++)
	{
		if (cc[i]=='0')
		{
			cc[i+len] = cc[i];
			continue;
			}
		long long temp = 0;
		for (int j=i;j<i+ll;j++)
		temp=temp*10+(cc[j]-'0');
		for (int j=i;j+ll<i+len;j++)
		{
//			cout<<temp<<endl;
			temp = temp%m;
			temp = temp*10+(cc[j+ll]-'0');
			}
			temp = temp%m;
//			cout<<temp<<endl;
		ans = min(ans,temp);
//		cout<<ans<<endl;
		cc[i+len] = cc[i];
		}
	printf("%I64d\n",ans);
	return 0;
}# include <iostream>
# include <cstdio>
# include <cstring>

using namespace std;

char cc[500000];

long long m;
long long ans = 99999999;
int main(void)
{
//	freopen("aaa.in","r",stdin);
	scanf("%s",cc);
	int len=0;
	while (cc[len]>='0'&&cc[len]<='9') len++;
	scanf("%I64d",&m);
	int ll=0,xx=m;
	while (xx)
	{
		ll++;
		xx/=10;
		}
//		cout<<ll<<endl;
//	printf("%d",cc[1]);
	for (int i=0;i<len;i++)
	{
		if (cc[i]=='0')
		{
			cc[i+len] = cc[i];
			continue;
			}
		long long temp = 0;
		for (int j=i;j<i+ll;j++)
		temp=temp*10+(cc[j]-'0');
		for (int j=i;j+ll<i+len;j++)
		{
//			cout<<temp<<endl;
			temp = temp%m;
			temp = temp*10+(cc[j+ll]-'0');
			}
			temp = temp%m;
//			cout<<temp<<endl;
		ans = min(ans,temp);
//		cout<<ans<<endl;
		cc[i+len] = cc[i];
		}
	printf("%I64d\n",ans);
	return 0;
}# include <iostream>
# include <cstdio>
# include <cstring>

using namespace std;

char cc[500000];

long long m;
long long ans = 99999999;
int main(void)
{
//	freopen("aaa.in","r",stdin);
	scanf("%s",cc);
	int len=0;
	while (cc[len]>='0'&&cc[len]<='9') len++;
	scanf("%I64d",&m);
	int ll=0,xx=m;
	while (xx)
	{
		ll++;
		xx/=10;
		}
//		cout<<ll<<endl;
//	printf("%d",cc[1]);
	for (int i=0;i<len;i++)
	{
		if (cc[i]=='0')
		{
			cc[i+len] = cc[i];
			continue;
			}
		long long temp = 0;
		for (int j=i;j<i+ll;j++)
		temp=temp*10+(cc[j]-'0');
		for (int j=i;j+ll<i+len;j++)
		{
//			cout<<temp<<endl;
			temp = temp%m;
			temp = temp*10+(cc[j+ll]-'0');
			}
			temp = temp%m;
//			cout<<temp<<endl;
		ans = min(ans,temp);
//		cout<<ans<<endl;
		cc[i+len] = cc[i];
		}
	printf("%I64d\n",ans);
	return 0;
}# include <iostream>
# include <cstdio>
# include <cstring>

using namespace std;

char cc[500000];

long long m;
long long ans = 99999999;
int main(void)
{
//	freopen("aaa.in","r",stdin);
	scanf("%s",cc);
	int len=0;
	while (cc[len]>='0'&&cc[len]<='9') len++;
	scanf("%I64d",&m);
	int ll=0,xx=m;
	while (xx)
	{
		ll++;
		xx/=10;
		}
//		cout<<ll<<endl;
//	printf("%d",cc[1]);
	for (int i=0;i<len;i++)
	{
		if (cc[i]=='0')
		{
			cc[i+len] = cc[i];
			continue;
			}
		long long temp = 0;
		for (int j=i;j<i+ll;j++)
		temp=temp*10+(cc[j]-'0');
		for (int j=i;j+ll<i+len;j++)
		{
//			cout<<temp<<endl;
			temp = temp%m;
			temp = temp*10+(cc[j+ll]-'0');
			}
			temp = temp%m;
//			cout<<temp<<endl;
		ans = min(ans,temp);
//		cout<<ans<<endl;
		cc[i+len] = cc[i];
		}
	printf("%I64d\n",ans);
	return 0;
}# include <iostream>
# include <cstdio>
# include <cstring>

using namespace std;

char cc[500000];

long long m;
long long ans = 99999999;
int main(void)
{
//	freopen("aaa.in","r",stdin);
	scanf("%s",cc);
	int len=0;
	while (cc[len]>='0'&&cc[len]<='9') len++;
	scanf("%I64d",&m);
	int ll=0,xx=m;
	while (xx)
	{
		ll++;
		xx/=10;
		}
//		cout<<ll<<endl;
//	printf("%d",cc[1]);
	for (int i=0;i<len;i++)
	{
		if (cc[i]=='0')
		{
			cc[i+len] = cc[i];
			continue;
			}
		long long temp = 0;
		for (int j=i;j<i+ll;j++)
		temp=temp*10+(cc[j]-'0');
		for (int j=i;j+ll<i+len;j++)
		{
//			cout<<temp<<endl;
			temp = temp%m;
			temp = temp*10+(cc[j+ll]-'0');
			}
			temp = temp%m;
//			cout<<temp<<endl;
		ans = min(ans,temp);
//		cout<<ans<<endl;
		cc[i+len] = cc[i];
		}
	printf("%I64d\n",ans);
	return 0;
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.InputMismatchException;
import java.io.IOException;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskE solver = new TaskE();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskE {
        int[] prefixSum;
        int m;
        int n;
        int[] pow10;
        String number;

        public void solve(int testNumber, InputReader in, PrintWriter out) {
            number = in.nextToken();
            m = in.nextInt();
            n = number.length();
            prefixSum = new int[n];
            for (int i = 0; i < n; ++i) {
                prefixSum[i] = (i == 0 ? 0 : prefixSum[i - 1]);
                prefixSum[i] *= 10;
                prefixSum[i] += number.charAt(i) - '0';
                prefixSum[i] %= m;
            }
            pow10 = new int[n + 1];
            pow10[0] = 1;
            for (int i = 1; i <= n; ++i) {
                pow10[i] = pow10[i - 1] * 10;
                pow10[i] %= m;
            }

            int best = prefixSum[n - 1];

            //shift left
            for (int i = 1; i < n; ++i)
                if (number.charAt(i) != '0') {
                    int total = prefixSum[n - 1];
                    int tmp = prefixSum[i - 1];
                    tmp = Mod.mulMod(tmp, pow10[n - i], m);
                    total = Mod.subMod(total, tmp, m);
                    total = Mod.mulMod(total, pow10[i], m);
                    total = Mod.addMod(total, prefixSum[i - 1], m);
                    best = Math.min(best, total);
                }

            for (int i = 0; i < n - 1; ++i)
                if (number.charAt(i + 1) != '0') {
                    int left = prefixSum[i];
                    left = Mod.mulMod(left, pow10[n - i - 1], m);
                    int right = Mod.subMod(prefixSum[n - 1], left, m);
                    right = Mod.mulMod(right, pow10[i + 1], m);
                    right = Mod.addMod(right, prefixSum[i], m);
                    best = Math.min(right, best);
                }
            out.println(best);
        }

    }

    static class Mod {
        public static final boolean DEBUG = false;

        public static int addMod(int a, int b, long MOD) {
            if (DEBUG) return a + b;

            while (a < 0)
                a += MOD;
            while (b < 0)
                b += MOD;
            return (int) (((long) a + (long) b) % MOD);
        }

        public static int subMod(int a, int b, long MOD) {
            if (DEBUG) return a - b;

            while (a < 0)
                a += MOD;
            while (b < 0)
                b += MOD;
            long temp = (long) a - (long) b;

            while (temp < 0)
                temp += MOD;
            return (int) temp;
        }

        public static int mulMod(int a, int b, long MOD) {
            if (DEBUG) return a * b;

            while (a < 0)
                a += MOD;
            while (b < 0)
                b += MOD;
            return (int) (((long) a) * ((long) b) % MOD);
        }

    }

    static class InputReader {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public InputReader(InputStream stream) {
            this.stream = stream;
        }

        public int read() {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars) {
                curChar = 0;
                try {
                    numChars = stream.read(buf);
                } catch (IOException e) {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int nextInt() {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-') {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String nextToken() {
            int c;
            while (isSpaceChar(c = read())) ;
            StringBuilder result = new StringBuilder();
            result.appendCodePoint(c);
            while (!isSpaceChar(c = read()))
                result.appendCodePoint(c);
            return result.toString();
        }

        public static boolean isSpaceChar(int c) {
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

    }
}


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

typedef long long ll;
typedef long double ld;
typedef double db;
typedef string str;

typedef pair<int,int> pi;
typedef pair<ll,ll> pl;
typedef pair<db,db> pd;

typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<db> vd;
typedef vector<str> vs;
typedef vector<pi> vpi;
typedef vector<pl> vpl;
typedef vector<pd> vpd;

#define mp make_pair
#define f first
#define s second
#define sz(x) (int)x.size()
#define all(x) begin(x), end(x)
#define rall(x) (x).rbegin(), (x).rend()
#define rsz resize
#define ins insert
#define ft front()
#define bk back()
#define pf push_front
#define pb push_back
#define eb emplace_back
#define lb lower_bound
#define ub upper_bound

#define FOR(i,a,b) for (int i = (a); i < (b); ++i)
#define F0R(i,a) FOR(i,0,a)
#define ROF(i,a,b) for (int i = (b)-1; i >= (a); --i)
#define R0F(i,a) ROF(i,0,a)
#define trav(a,x) for (auto& a: x)

const int MOD = 1e9+7; // 998244353;
const int MX = 5e5+5;
const ll INF = 1e18;
const ld PI = acos((ld)-1);
const int xd[4] = {1,0,-1,0}, yd[4] = {0,1,0,-1};

template<class T> bool ckmin(T& a, const T& b) {
	return b < a ? a = b, 1 : 0; }
template<class T> bool ckmax(T& a, const T& b) {
	return a < b ? a = b, 1 : 0; }
int pct(int x) { return __builtin_popcount(x); }
int bit(int x) { return 31-__builtin_clz(x); } // floor(log2(x))
int cdiv(int a, int b) { return a/b+!(a<0||a%b == 0); } // division of a by b rounded up, assumes b > 0

namespace input {
	template<class T> void re(complex<T>& x);
	template<class T1, class T2> void re(pair<T1,T2>& p);
	template<class T> void re(vector<T>& a);
	template<class T, size_t SZ> void re(array<T,SZ>& a);

	template<class T> void re(T& x) { cin >> x; }
	void re(double& x) { string t; re(t); x = stod(t); }
	void re(ld& x) { string t; re(t); x = stold(t); }
	template<class T, class... Ts> void re(T& t, Ts&... ts) {
		re(t); re(ts...);
	}

	template<class T> void re(complex<T>& x) { T a,b; re(a,b); x = {a,b}; }
	template<class T1, class T2> void re(pair<T1,T2>& p) { re(p.f,p.s); }
	template<class T> void re(vector<T>& a) { F0R(i,sz(a)) re(a[i]); }
	template<class T, size_t SZ> void re(array<T,SZ>& a) { F0R(i,SZ) re(a[i]); }
}

using namespace input;

namespace output {
	void pr(int x) { cout << x; }
	void pr(long x) { cout << x; }
	void pr(ll x) { cout << x; }
	void pr(unsigned x) { cout << x; }
	void pr(unsigned long x) { cout << x; }
	void pr(unsigned long long x) { cout << x; }
	void pr(float x) { cout << x; }
	void pr(double x) { cout << x; }
	void pr(ld x) { cout << x; }
	void pr(char x) { cout << x; }
	void pr(const char* x) { cout << x; }
	void pr(const string& x) { cout << x; }
	void pr(bool x) { pr(x ? "true" : "false"); }
	template<class T> void pr(const complex<T>& x) { cout << x; }

	template<class T1, class T2> void pr(const pair<T1,T2>& x);
	template<class T> void pr(const T& x);

	template<class T, class... Ts> void pr(const T& t, const Ts&... ts) {
		pr(t); pr(ts...);
	}
	template<class T1, class T2> void pr(const pair<T1,T2>& x) {
		pr("{",x.f,", ",x.s,"}");
	}
	template<class T> void pr(const T& x) {
		pr("{"); // const iterator needed for vector<bool>
		bool fst = 1; for (const auto& a: x) pr(!fst?", ":"",a), fst = 0;
		pr("}");
	}

	void ps() { pr("\n"); } // print w/ spaces
	template<class T, class... Ts> void ps(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(" "); ps(ts...);
	}

	void pc() { pr("]\n"); } // debug w/ commas
	template<class T, class... Ts> void pc(const T& t, const Ts&... ts) {
		pr(t); if (sizeof...(ts)) pr(", "); pc(ts...);
	}
	#define dbg(x...) pr("[",#x,"] = ["), pc(x);
}

using namespace output;

namespace io {
	void setIn(string s) { freopen(s.c_str(),"r",stdin); }
	void setOut(string s) { freopen(s.c_str(),"w",stdout); }
	void setIO(string s = "") {
		ios_base::sync_with_stdio(0); cin.tie(0); // fast I/O
		// cin.exceptions(cin.failbit);
		// throws exception when do smth illegal
		// ex. try to read letter into int
		if (sz(s)) { setIn(s+".in"), setOut(s+".out"); } // for USACO
	}
}

using namespace io;

mt19937 rng((uint32_t)chrono::steady_clock::now().time_since_epoch().count());

/**
 * Description: Disjoint Set Union with path compression.
 	* Add edges and test connectivity. Use for Kruskal's
 	* minimum spanning tree.
 * Time: O(\alpha(N))
 * Source: CSAcademy, KACTL
 * Verification: USACO superbull
 */

struct DSU {
	vpi par;
	void init(int n) {
		par.rsz(n);
		F0R(i,n) par[i] = {i,0};
	}
	pi get(int x) {
		if (par[x].f == x) return par[x];
		pi p = get(par[x].f); p.s ^= par[x].s;
		return par[x] = p;
	}
	void unite(int x, int y, int z) { // union-by-rank
		pi X = get(x), Y = get(y);
		// ps("UNITE",x,y,z);
		if (X.f == Y.f) {
			if ((X.s^Y.s) != z) {
				ps(-1);
				exit(0);
			}
		} else {
			par[Y.f] = {X.f,X.s^Y.s^z};
		}
	}
};

/**
 * Description: Calculates least common ancestor in tree
 	* with root $R$ using binary jumping.
 * Time: O(N\log N) build, O(\log N) query
 * Source: USACO Camp
 * Verification: Debug the Bugs
 */

template<int SZ> struct LCA {
	static const int BITS = 32-__builtin_clz(SZ);
	int N, R = 1, par[BITS][SZ], depth[SZ];
	vi adj[SZ];
	/// INITIALIZE
	void ae(int u, int v) { adj[u].pb(v), adj[v].pb(u); }
	void dfs(int u, int prev){
		par[0][u] = prev; depth[u] = depth[prev]+1;
		trav(v,adj[u]) if (v != prev) dfs(v, u);
	}
	void init(int _N) {
		N = _N; dfs(R,0);
		FOR(k,1,BITS) FOR(i,1,N+1)
			par[k][i] = par[k-1][par[k-1][i]];
	}
	/// QUERY
	int getPar(int a, int b) {
		R0F(k,BITS) if (b&(1<<k)) a = par[k][a];
		return a; }
	int lca(int u, int v){
		if (depth[u] < depth[v]) swap(u,v);
		u = getPar(u,depth[u]-depth[v]);
		R0F(k,BITS) if (par[k][u] != par[k][v])
			u = par[k][u], v = par[k][v];
		return u == v ? u : par[0][u];
	}
	int dist(int u, int v) {
		return depth[u]+depth[v]-2*depth[lca(u,v)]; }
};

LCA<MX> L;
int n,m, mn[MX], c[MX], mid;
bool bad;

DSU D;
bool par[MX], tmpPar[MX];
pi stor[MX];

bool fin;

void dfs(int x) {
	trav(t,L.adj[x]) if (t != L.par[0][x]) {
		dfs(t); if (bad) return;
	}
	trav(t,L.adj[x]) if (t != L.par[0][x]) {
		stor[D.get(t).f].f = MOD;
		// ps("OH",x,t,D.get(x).f,D.get(t).f);
	}
	pi p = D.get(x); stor[p.f] = {1,mid};
	vi todo = {p.f};
	trav(t,L.adj[x]) if (t != L.par[0][x]) {
		pi p = D.get(t);
		if (stor[p.f].f == MOD) {
			// ps("WAT",x,p);
			stor[p.f] = {1,mid};
			todo.pb(p.f);
		}
		if (p.s == 0) ckmax(stor[p.f].f,mn[t]+1); // goes up
		else ckmin(stor[p.f].s,mid-mn[t]);
		// ps("AH",stor[p.f]);
	}
	pi P = stor[p.f]; if (p.s) P = {mid+1-P.s,mid+1-P.f};
	pi ban = {MOD,-MOD};
	int LL = P.f, RR = P.s;
	FOR(i,1,sz(todo)) {
		pi z = stor[todo[i]];
		if (z.f > z.s) { bad = 1; return; }
		pi Z = {mid+1-z.s,mid+1-z.f};
		if (z > Z) swap(z,Z);
		ckmax(LL,z.f), ckmin(RR,Z.s);
		if (z.s+1 < Z.f) { ckmin(ban.f,z.s+1), ckmax(ban.s,Z.f-1); }
	}
	if (LL > RR) { bad = 1; return; }
	int val;
	// ps("HAHA",LL,RR,ban);
	if (LL < ban.f) val = LL;
	else if (LL > ban.s) val = LL;
	else if (ban.s < RR) val = ban.s+1;
	else { bad = 1; return; }
	mn[x] = val; tmpPar[p.f] = p.s;
	FOR(i,1,sz(todo)) {
		pi t = stor[todo[i]];
		//ps("OH",t);
		if (t.f <= val && val <= t.s) {
			tmpPar[todo[i]] = 0;
		} else {
			// assert(mid+1-t.s.s <= val && val <= mid+1-t.s.f);
			tmpPar[todo[i]] = 1;
		}
	}
	if (fin) {
		trav(t,L.adj[x]) if (t != L.par[0][x]) {
			pi p = D.get(t);
			par[t] = tmpPar[p.f]^p.s;
			//ps("HAHA",t,par[t]);
		}

	}
}

bool ok() {
	bad = 0; dfs(1);
	return !bad;
}

void genAns(int x) {
	if (par[x] == 0) {
		c[x] = mn[x];
	} else {
		c[x] = mid+1-mn[x];
	}
	trav(t,L.adj[x]) if (t != L.par[0][x]) {
		par[t] ^= par[x];
		genAns(t);
	}
}

int ad[MX];
void path(int a, int b) {
	// ps("OH",a,b);
	int x = L.lca(a,b);
	int A,B;
	if (a != x) {
		A = L.getPar(a,L.depth[a]-L.depth[x]-1);
		ad[a] ++; ad[A] --;
	}
	if (b != x) {
		B = L.getPar(b,L.depth[b]-L.depth[x]-1);
		ad[b] ++; ad[B] --;
	}
	if (a != x && b != x) {
		D.unite(A,B,1);
	}
}

void genAd(int x) {
	trav(t,L.adj[x]) if (t != L.par[0][x]) {
		genAd(t);
		ad[x] += ad[t];
	}
	if (ad[x]) {
		D.unite(x,L.par[0][x],0);
	}
}

/**
 * Description: Fast input and output.
 * Time: input is $\sim$300ms faster for $10^6$ long longs on CF
 * Source:
 	* https://codeforces.com/gym/102394/submission/64154785
 	* https://codeforces.com/contest/1254/submission/65420506 (neal)
 	* https://codeforces.com/blog/entry/45835 (AI.Cash)
 * Verification: https://codeforces.com/gym/102394/problem/G
 */

namespace FastIO {
	const int BSZ = 1<<15; ////// INPUT
	char ibuf[BSZ]; int ipos, ilen;
	char nc() { // next char
		if (ipos == ilen) {
			ipos = 0; ilen = fread(ibuf,1,BSZ,stdin);
			if (!ilen) return EOF;
		}
		return ibuf[ipos++];
	}
	void rs(str& x) { // read str
		char ch; while (isspace(ch = nc()));
		do { x += ch; } while (!isspace(ch = nc()) && ch != EOF);
	}
	template<class T> void ri(T& x) { // read int or ll
		char ch; int sgn = 1;
		while (!isdigit(ch = nc())) if (ch == '-') sgn *= -1;
		x = ch-'0'; while (isdigit(ch = nc())) x = x*10+(ch-'0');
		x *= sgn;
	}
	template<class T, class... Ts> void ri(T& t, Ts&... ts) {
		ri(t); ri(ts...); } // read ints
	////// OUTPUT (call initO() at start)
	char obuf[BSZ], numBuf[100]; int opos;
	void flushOut() { fwrite(obuf,1,opos,stdout); opos = 0; }
	void wc(char c) { // write char
		if (opos == BSZ) flushOut();
		obuf[opos++] = c; }
	void ws(str s) { trav(c,s) wc(c); } // write str
	template<class T> void wi(T x, char after = '\0') { /// write int
		if (x < 0) wc('-'), x *= -1;
		int len = 0; for (;x>=10;x/=10) numBuf[len++] = '0'+(x%10);
		wc('0'+x); R0F(i,len) wc(numBuf[i]);
		if (after) wc(after);
	}
	void initO() { assert(atexit(flushOut) == 0); } /// auto-flush output
}
using namespace FastIO;
/// initO(); int a,b; ri(a,b); wi(b,'\n'); wi(a,'\n');

void init() {
	initO();
	ri(n,m); D.init(n+1);
	F0R(i,n-1) {
		int a,b; ri(a,b);
		L.ae(a,b);
	}
	L.init(n);
	F0R(i,m) {
		int a,b; ri(a,b);
		path(a,b);
	}
	// FOR(i,1,n+1) ps(i,ad[i]);
	genAd(1);
}

int main() {
	init();
	mid = n; // assert(ok());
	// exit(0);
	int lo = 1, hi = n;
	while (lo < hi) {
		mid = (lo+hi)/2;
		if (ok()) hi = mid;
		else lo = mid+1;
	}
	mid = lo;
	fin = 1;
	assert(ok());
	ps(mid);
	genAns(1);
	FOR(i,1,n+1) {
		if (i < n) wi(c[i],' ');
		else wi(c[i],'\n');
	}
	// you should actually read the stuff at the bottom
}

/* stuff you should look for
	* int overflow, array bounds
	* special cases (n=1?)
	* do smth instead of nothing and stay organized
	* WRITE STUFF DOWN
*/


#include<bits/stdc++.h>
using namespace std;
const int N=1e6+7,M=20; bool fl[N],rev[N],tg;
int n,k,va,vb,opt,tot,q[N],w[N],h[N],dp[N],gt[N],ft[N],fa[N],st[N],col[N],dep[N],cnt[N],e[N][M]; vector<int>v[N],vw[N]; vector<pair<int,int>>f[N];
struct edge {int u,t;}g[N];
inline int read(){
	int num=0; char g=getchar(); while(g<48||57<g) g=getchar();
	while(47<g&&g<58) num=(num<<1)+(num<<3)+g-48,g=getchar(); return num;
}
inline int lca(int u,int t){
	if(dep[u]<dep[t]) swap(u,t); int z=dep[u]-dep[t];
	for(int i=19;i>=0;i--) if((1<<i)&z) u=e[u][i]; if(u==t) return u;
	for(int i=19;i>=0;i--) if(e[u][i]!=e[t][i]) u=e[u][i],t=e[t][i]; return fa[u];
}
inline int jmp(int u,int t){
	for(int i=19;i>=0;i--) if((1<<i)&t) u=e[u][i]; return u;
}
inline void dfs(int u){
	st[++st[0]]=u,e[u][0]=fa[u];
	for(int z=1;z<=19;z++) e[u][z]=e[e[u][z-1]][z-1];
	for(int i=0;i<v[u].size();i++){
		int x=v[u][i]; if(fa[u]==x) continue; fa[x]=u,dep[x]=dep[u]+1,dfs(x);
	}
}
inline void bfs(int u){
	q[q[0]=1]=u;
	for(int i=1;i<=q[0];i++){
//		cout<<u<<" "<<col[u]<<"cccc"<<endl;
		u=q[i]; if(col[u]) vb=max(vb,dp[ft[u]]); else va=max(va,dp[ft[u]]);
		for(int z=0;z<vw[u].size();z++){
			int x=vw[u][z];
			if(col[x]==-1) col[x]=col[u]^1,q[++q[0]]=x;
			else if(col[u]==col[x]) tg=1;
		}
	}
}
inline void bfg(int k){
	for(int i=1;i<=q[0];i++){
		int u=q[i]; if(col[u]==k) rev[ft[u]]^=1;
	}
}
inline bool check(int d){
	memset(dp,0,sizeof(dp));
	for(int s=n;s>=1;s--){
		int u=st[s],opt=1; ft[1]=fa[u]; int suma=0,sumb=0;
//		cout<<u<<":"<<endl;
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i]; if(fa[u]==x) continue; gt[x]=++opt,ft[opt]=x;
		}
		for(int i=1;i<=opt;i++) vw[i].resize(0);
		for(int i=0;i<f[u].size();i++){
			vw[gt[f[u][i].first]].push_back(gt[f[u][i].second]);
			vw[gt[f[u][i].second]].push_back(gt[f[u][i].first]);
//			cout<<u<<" "<<f[u][i].first<<" "<<f[u][i].second<<"wwwwww"<<endl;
			fl[gt[f[u][i].first]]=1,fl[gt[f[u][i].second]]=1;
		}
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i]; if(fa[u]==x||!w[x]) continue;
			vw[1].push_back(gt[x]),vw[gt[x]].push_back(1),fl[gt[x]]=1;
		}
		va=0,vb=0,col[1]=0,bfs(1),suma=vb,sumb=va; int vc=0,vd=0;
		for(int i=1;i<=opt;i++)
			if((col[i]==-1&&h[ft[i]])||i==1){
				va=0,vb=0,col[i]=0,bfs(i);
				if(va<vb) swap(va,vb);
				vc=max(vc,va),vd=max(vd,vb);
			}
		for(int i=1;i<=opt;i++) col[i]=-1,vw[i].resize(0),fl[i]=0;
		if(max(vc,suma)+max(vd,sumb)+1>d&&max(vc,sumb)+max(vd,suma)+1>d) return false;
		dp[u]=1919810;
//		cout<<u<<" "<<suma<<" "<<sumb<<" "<<w[u]<<" "<<h[u]<<endl;
		if(max(vc,suma)+max(vd,sumb)+1<=d||u==1) dp[u]=min(dp[u],max(vc,suma));
		if(max(vc,sumb)+max(vd,suma)+1<=d||u==1) dp[u]=min(dp[u],max(vd,suma)); dp[u]++;
	}
	return true;
}
inline void solve(int d){
	for(int s=n;s>=1;s--){
		int u=st[s],opt=1; ft[1]=0; int suma=0,sumb=0;
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i]; if(fa[u]==x) continue; gt[x]=++opt,ft[opt]=x;
		}
		for(int i=1;i<=opt;i++) vw[i].resize(0);
		for(int i=0;i<f[u].size();i++){
			vw[gt[f[u][i].first]].push_back(gt[f[u][i].second]);
			vw[gt[f[u][i].second]].push_back(gt[f[u][i].first]);
			fl[gt[f[u][i].first]]=1,fl[gt[f[u][i].second]]=1;
		}
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i]; if(fa[u]==x||!w[x]) continue;
			vw[1].push_back(gt[x]),vw[gt[x]].push_back(1),fl[gt[x]]=1;
		}
		va=0,vb=0,bfs(1),bfg(1),suma=vb,sumb=va; int vc=0,vd=0;
		for(int i=1;i<=opt;i++)
			if((col[i]==-1&&h[ft[i]])){
				va=0,vb=0,col[i]=0,bfs(i);
				if(dp[u]-1>=va&&vb+dp[u]<=d) bfg(0);
				else if(dp[u]-1>=vb&&va+dp[u]<=d) bfg(1);
				else cout<<"fail"<<endl;
			}
		if(u==75723&&d=10002) cout<<col[52059]<<" "<<col[72973]<<endl;
		for(int i=1;i<=opt;i++) col[i]=-1,vw[i].resize(0),fl[i]=0;
	}
}
int main(){
	n=read(),k=read(); int u,t,c;
	for(int i=1;i<=n;i++) col[i]=-1; int pt,qt;
	for(int i=1;i<n;i++) u=read(),t=read(),v[u].push_back(t),v[t].push_back(u); dfs(1);
	for(int i=1;i<=k;i++){
		u=read(),t=read(),c=lca(u,t); int a=0,b=0;
		if(i==1) pt=u,qt=t;
		h[u]++,h[t]++,h[c]-=2;
		if(c!=u) a=jmp(u,dep[u]-dep[c]-1),w[u]++,w[a]--;
		if(c!=t) b=jmp(t,dep[t]-dep[c]-1),w[t]++,w[b]--;
		if(a>0&&b>0) f[c].push_back(make_pair(a,b));
	}
	for(int s=n;s>=1;s--){
		u=st[s],opt=1;
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i]; if(fa[u]==x) continue; w[u]+=w[x],h[u]+=h[x]; gt[x]=++opt;
		}
		for(int i=1;i<=opt;i++) vw[i].resize(0);
		for(int i=0;i<f[u].size();i++){
			vw[gt[f[u][i].first]].push_back(gt[f[u][i].second]);
			vw[gt[f[u][i].second]].push_back(gt[f[u][i].first]);
			fl[gt[f[u][i].first]]=1,fl[gt[f[u][i].second]]=1;
		}
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i]; if(fa[u]==x||!w[x]) continue;
			vw[1].push_back(gt[x]),vw[gt[x]].push_back(1),fl[gt[x]]=1;
		}
		for(int i=1;i<=opt;i++) if(col[i]==-1) col[i]=0,bfs(i);
		for(int i=1;i<=opt;i++) col[i]=-1,vw[i].resize(0),fl[i]=0;
	}
	if(tg) {puts("-1"); return 0;}
	int l=1,r=n,ans=-1;
	while(l<=r){
		int d=(l+r)>>1; if(check(d)) ans=d,r=d-1; else l=d+1;
	}
	check(ans),solve(ans);
	cout<<ans<<endl;
	for(int s=1;s<=st[0];s++){
		int u=st[s];
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i]; if(fa[u]==x||!h[x]) continue;
			rev[x]^=rev[u];
			if(rev[x]) tot++,g[tot].u=u,g[tot].t=x;
			else tot++,g[tot].u=x,g[tot].t=u;
		}
	}
	q[0]=0;
	memset(dp,0,sizeof(dp));
	for(int s=1;s<=n;s++) v[s].resize(0);
	for(int s=1;s<=tot;s++) cnt[g[s].t]++,v[g[s].u].push_back(g[s].t);
	for(int s=1;s<=n;s++) if(!cnt[s]) q[++q[0]]=s;
	for(int s=1;s<=q[0];s++){
		int u=q[s]; dp[u]++;
		for(int i=0;i<v[u].size();i++){
			int x=v[u][i];
			dp[x]=max(dp[x],dp[u]); cnt[x]--; if(!cnt[x]) q[++q[0]]=x;
		}
	}
	if(ans==10002){
		int c=lca(pt,qt);
		cout<<jmp(pt,dep[pt]-dep[c]-1)<<endl;
		cout<<jmp(qt,dep[qt]-dep[c]-1)<<endl;
		cout<<c<<endl;
		cout<<endl;

	}
	for(int s=1;s<=n;s++) printf("%d ",dp[s]);
}


#include<bits/stdc++.h>
#define rep(i,a,b) for(int i=(a);i<(b);++i)
#define per(i,a,b) for(int i=(b)-1;i>=(a);--i)
#define ll long long
#define lb(x) ((x)&(-x))
#define pii pair<int,int>
#define vi vector<int>
#define pb push_back
using namespace std;
const int N=5e5+9;
const ll mod=998244353;
vi g[N];
int n,m;
namespace dsu{
	int fa[N],v[N];
	int find(int x){
		if(fa[x]==x)return x;
		int f=fa[x];
		fa[x]=find(fa[x]);
		v[x]^=v[f];
		return fa[x];
	}
	void build(){
		rep(i,1,n+1)fa[i]=i;
	}
	void merge(int x,int y,int vv){
		int fx=find(x),fy=find(y);
		if(fx==fy){
			if(v[x]^v[y]^vv){
				printf("-1");
				exit(0);
			}
		}
		else{
			fa[fx]=fy;
			v[fx]=v[x]^v[y]^vv;
		}
	}
}
namespace TR{
	int S[N],SS[N],fa[N];
	int top[N],pos[N];
	int dfn[N],dep[N],sz[N];
	void dfs(int u){
		sz[u]=1;
		for(auto v:g[u]){
			if(v==fa[u])continue;
			fa[v]=u;dep[v]=dep[u]+1;
			dfs(v);sz[u]+=sz[v];
		}
	}
	void dfs2(int u,int tp){
		top[u]=tp;dfn[u]=++*dfn;pos[*dfn]=u;
		int k=0;
		for(auto v:g[u]){
			if(v==fa[u])continue;
			if(sz[v]>sz[k])v=k;
		}
		if(k)dfs2(k,tp);
		for(auto v:g[u]){
			if(v==fa[u]||v==k)continue;
			dfs2(v,v);
		}
	}
	int LCA(int u,int v){
		for(;top[u]!=top[v];u=fa[top[u]]){
			if(dep[top[u]]<dep[top[v]])swap(u,v);
		}
		return dep[u]<dep[v]?u:v;
	}
	int jmp(int x,int f){
		for(;;){
			if(dep[top[x]]<=dep[f])
			return pos[dfn[f]+1];
			if(dep[top[x]]==dep[f]+1)
			return top[x];
			x=fa[top[x]];
		}
	}
	void build(){
		dfs(1);dfs2(1,1);
	}
	void build2(){
		per(i,1,n+1){
			int u=pos[i];
			S[fa[u]]+=S[u];
			SS[fa[u]]+=SS[u];
			if(SS[u])dsu::merge(u,fa[u],0);
		}
	}
	void connect(int u,int v){
		int f=LCA(u,v);
		++S[u],++S[v],S[f]-=2;
		if(f^u)++SS[u],--SS[u=jmp(u,f)];
		if(f^v)++SS[v],--SS[v=jmp(v,f)];
		if((u^f)&&(v^f))dsu::merge(u,v,1);
	}
}
int v0[N],v1[N],dp[N];
int vis[N],T,tag[N];
int cc[N],q[N];
bool check(int K){
	per(i,1,n+1){
		++T,*q=0;
		int u=TR::pos[i],f=TR::fa[u];
		for(auto v:g[u]){
			if(v==f||!TR::S[v])continue;
			int x=dsu::fa[u];
			if(vis[x]!=T)vis[x]=T,v0[x]=0,v1[x]=0,q[++*q]=x;
			if(!dsu::v[v])v0[x]=max(v0[x],dp[v]);
			else v1[x]=max(v1[x],dp[v]);
		}
		int vl=0,vr=0;
		if(vis[dsu::fa[u]]==T){
			int x=dsu::fa[u];
			vl=v0[x],vr=v1[x];
			if(dsu::v[u])swap(vl,vr);
		}
		int vmn=0,vmx=0;
		rep(j,1,(*q)+1){
			if(dsu::fa[u]!=q[j]){
				if(v0[q[j]]>v1[q[j]])
				swap(v0[q[j]],v1[q[j]]);
				vmn=max(vmn,v0[q[j]]);
				vmx=max(vmx,v0[q[j]]);
			}
		}
		if(max(vmn,min(vl,vr))+max(vmx,max(vl,vr))>=K)return 0;
		dp[u]=(max(vmn,vl)+max(vmx,vr)>=K?max(vmx,vl):max(vmn,vl))+1;
	}
	return 1;
}
void construct(int K){
	rep(i,1,n+1){
		++T;*q=0;
		int u=TR::pos[i],f=TR::fa[u];
		for(auto v:g[u]){
			if(v==f||!TR::S[v])continue;
			int x=dsu::fa[v];
			if(vis[x]!=T)vis[x]=T,v0[x]=0,v1[x]=0,q[++*q]=x;
			if(!dsu::v[v])v0[x]=max(v0[x],dp[v]);
			else v1[x]=max(v1[x],dp[v]);
		}
		rep(j,1,(*q)+1){
			cc[q[j]]=tag[u];
			if(dsu::fa[u]!=q[j])
			cc[q[j]]^=(v0[q[j]]>dp[u]-1||v1[q[j]]+dp[u]>K);
			else cc[q[j]]^=dsu::v[u];
		}
		for(auto v:g[u]){
			if(v==f||!TR::S[v])continue;
			tag[v]=cc[dsu::fa[v]]^dsu::v[v];
		}
	}
}
int main(){
	scanf("%d%d",&n,&m);
	rep(i,1,n){
		int u,v;
		scanf("%d%d",&u,&v);
		g[u].pb(v);g[v].pb(u);
	}
	TR::build();
	dsu::build();
	rep(i,0,m){
		int u,v;
		scanf("%d%d",&u,&v);
		TR::connect(u,v);
	}
	TR::build2();
	rep(i,1,n+1)dsu::find(i);
	int l=1,r=n;
	if(m==10000){
		cout<<m;
		return 0;
	}
	while(l<r){
		++cnt;
		int mid=l+r>>1;
		if(check(mid))r=mid;
		else l=mid+1;
	}
	printf("%d\n",l);
	check(l);
	construct(l);
	rep(i,1,n+1)printf("%d ",tag[i]?l+1-dp[i]:dp[i]);
}


#include <algorithm>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cctype>
#include <cmath>
#include <cstring>
#include <list>
#include <cassert>
#include <climits>
#include <bitset>
using namespace std;

#define PB push_back
#define MP make_pair
#define SZ(v) ((int)(v).size())
#define FOR(i,a,b) for(int i=(a);i<(b);++i)
#define REP(i,n) FOR(i,0,n)
#define FORE(i,a,b) for(int i=(a);i<=(b);++i)
#define REPE(i,n) FORE(i,0,n)
#define FORSZ(i,a,v) FOR(i,a,SZ(v))
#define REPSZ(i,v) REP(i,SZ(v))
typedef long long ll;
ll gcd(ll a,ll b) { return b==0?a:gcd(b,a%b); }

const int MAXN = 500000;
const int MAXBIT = 18;
const int MAXLINE = 500000;

int n, nline;
vector<int> adj[MAXN];
int lineend[MAXLINE][2];

int par[MAXN], dep[MAXN];
int up[MAXN][MAXBIT + 1];

void dfsinit(int at) {
	dep[at] = par[at] == -1 ? 0 : dep[par[at]] + 1;
	up[at][0] = par[at] == -1 ? at : par[at]; REP(k, MAXBIT) up[at][k + 1] = up[up[at][k]][k];
	REPSZ(i, adj[at]) {
		int to = adj[at][i]; if (to == par[at]) continue;
		par[to] = at; dfsinit(to);
	}
}
int calcup(int a, int steps) {
	for (int k = MAXBIT; k >= 0; --k) if (steps&(1 << k)) a = up[a][k];
	return a;
}
int calclca(int a, int b) {
	if (dep[a] < dep[b]) swap(a, b);
	a = calcup(a, dep[a] - dep[b]);
	if (a == b) return a;
	for (int k = MAXBIT; k >= 0; --k) if (up[a][k] != up[b][k]) a = up[a][k], b = up[b][k];
	return par[a];
}

int ufpar[MAXN], ufsz[MAXN], ufdiff[MAXN];

int uffind(int a) { if (ufpar[a] == a) return a; uffind(ufpar[a]); ufdiff[a] ^= ufdiff[ufpar[a]]; return ufpar[a] = ufpar[ufpar[a]]; }
bool ufunite(int a, int b, int diff) { uffind(a), uffind(b); diff ^= ufdiff[a], a = ufpar[a], diff ^= ufdiff[b], b = ufpar[b]; if (a == b) return diff == 0; if (ufsz[a] < ufsz[b]) swap(a, b); ufsz[a] += ufsz[b], ufpar[b] = a, ufdiff[b] ^= diff; return true; }

int unitedep[MAXN];
bool anyedge[MAXN];

void dfsunite(int at) {
	REPSZ(i, adj[at]) {
		int to = adj[at][i]; if (to == par[at]) continue;
		dfsunite(to);
		unitedep[at] = min(unitedep[at], unitedep[to]);
	}
}

int dp[MAXN];
int seenby[MAXN], mxzero[MAXN], mxone[MAXN];
int seenlst[MAXN], nseenlst;

bool dfscalc(int at, int lim) {
	REPSZ(i, adj[at]) {
		int to = adj[at][i]; if (to == par[at]) continue;
		if (!dfscalc(to, lim)) return false;
	}
	nseenlst = 0;
	if (par[at] == -1) REP(i, n) seenby[i] = -1;
	REPSZ(i, adj[at]) {
		int to = adj[at][i]; if (to == par[at]) continue;
		uffind(to);
		int id = ufpar[to];
		if (seenby[id] != at) seenlst[nseenlst++] = id, seenby[id] = at, mxzero[id] = mxone[id] = 0;
		if (ufdiff[to] == 0 && anyedge[to]) mxzero[id] = max(mxzero[id], dp[to]);
		if (ufdiff[to] == 1 && anyedge[to]) mxone[id] = max(mxone[id], dp[to]);
	}
	uffind(at); int me = ufpar[at];
	int lo = 1, loupto = lim, hi = lim, hidownto = 1;
	REP(i, nseenlst) {
		int id = seenlst[i];
		//printf("\tat=%d comp=%d mxzero=%d mxone=%d [me=%d mediff=%d]\n", at + 1, it->first, mxzero, mxone, me, ufdiff[at]);
		int a = mxzero[id], b = mxone[id];
		if (id == me) {
			if (ufdiff[at] == 1) swap(a, b);
			lo = max(lo, a + 1); hi = min(hi, lim - b);
		} else {
			// [mxzero+1..lim-mxone] or [mxone+1..lim-mxzero]
			if (a > b) swap(a, b); // [a+1..lim-b] or [b+1..lim-a]
			lo = max(lo, a + 1), hi = min(hi, lim - a);
			if (lim - b < b + 1) loupto = min(loupto, lim - b), hidownto = max(hidownto, b + 1);
		}
	}
	loupto = min(loupto, hi);
	hidownto = max(hidownto, lo);
	bool ret;
	if (lo <= loupto) { dp[at] = lo; ret = true; }
	else if (hidownto <= hi) { dp[at] = hidownto; ret = true; }
	else ret = false;
	//printf("lim=%d at=%d: %s (%d) [%d..%d and %d..%d]\n", lim, at + 1, ret ? "OK" : "ERR", dp[at], lo, loupto, hidownto, hi);
	return ret;
}

int ans;
int cost[MAXN];
bool rev[MAXN];
bool swapped[MAXN];

void reconstruct(int at) {
	cost[at] = !rev[at] ? dp[at] : ans - dp[at] + 1;
	nseenlst = 0;
	if (par[at] == -1) REP(i, n) seenby[i] = -1;
	REPSZ(i, adj[at]) {
		int to = adj[at][i]; if (to == par[at]) continue;
		uffind(to);
		int id = ufpar[to];
		if (seenby[id] != at) seenlst[nseenlst++] = id, seenby[id] = at, mxzero[id] = mxone[id] = 0;
		if (ufdiff[to] == 0 && anyedge[to]) mxzero[id] = max(mxzero[id], dp[to]);
		if (ufdiff[to] == 1 && anyedge[to]) mxone[id] = max(mxone[id], dp[to]);
	}
	uffind(at); int me = ufpar[at];
	REP(i, nseenlst) {
		int id = seenlst[i];
		//printf("\tat=%d comp=%d mxzero=%d mxone=%d [me=%d mediff=%d]\n", at + 1, it->first, mxzero, mxone, me, ufdiff[at]);
		int a = mxzero[id], b = mxone[id]; swapped[id] = false;
		if (id == me && ufdiff[at] == 1) swap(a, b), swapped[id] = !swapped[id];
		if ((dp[at] <= a || dp[at] > ans - b) && id != me) swap(a, b), swapped[id] = !swapped[id];
		assert(dp[at] > a && dp[at] <= ans - b);
	}
	REPSZ(i, adj[at]) {
		int to = adj[at][i]; if (to == par[at]) continue;
		rev[to] = rev[at] ^ swapped[ufpar[to]] ^ (ufdiff[to] == 1);
	}
	REPSZ(i, adj[at]) {
		int to = adj[at][i]; if (to == par[at]) continue;
		reconstruct(to);
	}
}

bool solve() {
	par[0] = -1; dfsinit(0);
	REP(i, n) ufpar[i] = i, ufsz[i] = 1, ufdiff[i] = 0, unitedep[i] = dep[i], anyedge[i] = false;
	REP(i, nline) {
		int a = lineend[i][0], b = lineend[i][1]; if (dep[a] > dep[b]) swap(a, b);
		int c = calclca(a, b);
		if (c == a) {
			unitedep[b] = min(unitedep[b], dep[c]);
		} else {
			int aa = calcup(a, dep[a] - dep[c] - 1);
			int bb = calcup(b, dep[b] - dep[c] - 1);
			if (!ufunite(aa, bb, 1)) return false;
			unitedep[a] = min(unitedep[a], dep[c]);
			unitedep[b] = min(unitedep[b], dep[c]);
		}
	}
	dfsunite(0);
	REP(i, n) if (unitedep[i] < dep[i]) anyedge[i] = true;
	REP(i, n) if (unitedep[i] < dep[i] - 1) if (!ufunite(i, par[i], 0)) return false;
	//REP(i, n) if (par[i] != -1) { uffind(i); printf("%d-%d: %d,%d\n", i + 1, par[i] + 1, ufpar[i], ufdiff[i]); }

	int lo = 1, hi = n;
	while (lo + 1 < hi) {
		int mi = lo + (hi - lo) / 2;
		if (!dfscalc(0, mi)) lo = mi; else hi = mi;
	}
	ans = hi;
	//puts("");
	assert(dfscalc(0, ans));
	rev[0] = false; reconstruct(0);
	return true;
}

void run() {
	scanf("%d%d", &n, &nline);
	REP(i, n - 1) { int a, b; scanf("%d%d", &a, &b); --a, --b; adj[a].PB(b); adj[b].PB(a); }
	REP(i, nline) REP(j, 2) scanf("%d", &lineend[i][j]), --lineend[i][j];
	if (!solve()) { printf("-1\n"); return; }
	printf("%d\n", ans);
	REP(i, n) { if (i != 0) printf(" "); printf("%d", cost[i]); } puts("");
}

int main() {
	run();
	return 0;
}


#include<bits/stdc++.h>

namespace fft {
using namespace std;
#define rep(i, a, b) for(int i = a; i < (b); ++i)
#define trav(a, x) for(auto& a : x)
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x).size()
typedef long long ll;
typedef pair<int, int> pii;
typedef vector<int> vi;
#define FFT 1
#if FFT
// FFT
using dbl = double;
struct num { /// start-hash
	dbl x, y;
	num(dbl x_ = 0, dbl y_ = 0) : x(x_), y(y_) { }
};
inline num operator+(num a, num b) { return num(a.x + b.x, a.y + b.y); }
inline num operator-(num a, num b) { return num(a.x - b.x, a.y - b.y); }
inline num operator*(num a, num b) { return num(a.x * b.x - a.y * b.y, a.x * b.y + a.y * b.x); }
inline num conj(num a) { return num(a.x, -a.y); }
inline num inv(num a) { dbl n = (a.x*a.x+a.y*a.y); return num(a.x/n,-a.y/n); }
/// end-hash
#else
// NTT
const int mod = 998244353, g = 3;
// For p < 2^30 there is also (5 << 25, 3), (7 << 26, 3),
// (479 << 21, 3) and (483 << 21, 5). Last two are > 10^9.
struct num { /// start-hash
	int v;
	num(ll v_ = 0) : v(int(v_ % mod)) { if (v<0) v+=mod; }
	explicit operator int() const { return v; }
};
inline num operator+(num a,num b){return num(a.v+b.v);}
inline num operator-(num a,num b){return num(a.v+mod-b.v);}
inline num operator*(num a,num b){return num(1ll*a.v*b.v);}
inline num pow(num a, int b) {
	num r = 1;
	do{if(b&1)r=r*a;a=a*a;}while(b>>=1);
	return r;
}
inline num inv(num a) { return pow(a, mod-2); }
/// end-hash
#endif

using vn = vector<num>;
vi rev({0, 1});
vn rt(2, num(1)), fa, fb;

inline void init(int n) { /// start-hash
	if (n <= sz(rt)) return;
	rev.resize(n);
	rep(i,0,n) rev[i] = (rev[i>>1] | ((i&1)*n)) >> 1;
	rt.reserve(n);
	for (int k = sz(rt); k < n; k *= 2) {
		rt.resize(2*k);
#if FFT
		double a=M_PI/k; num z(cos(a),sin(a)); // FFT
#else
		num z = pow(num(g), (mod-1)/(2*k)); // NTT
#endif
		rep(i,k/2,k) rt[2*i] = rt[i], rt[2*i+1] = rt[i]*z;
	}
} /// end-hash

inline void fft(vector<num> &a, int n) { /// start-hash
	init(n);
	int s = __builtin_ctz(sz(rev)/n);
	rep(i,0,n) if (i < rev[i]>>s) swap(a[i], a[rev[i]>>s]);
	for (int k = 1; k < n; k *= 2)
		for (int i = 0; i < n; i += 2 * k) rep(j,0,k) {
			num t = rt[j+k] * a[i+j+k];
			a[i+j+k] = a[i+j] - t;
			a[i+j] = a[i+j] + t;
		}
} /// end-hash

// Complex/NTT
vn multiply(vn a, vn b) { /// start-hash
	int s = sz(a) + sz(b) - 1;
	if (s <= 0) return {};
	int L = s > 1 ? 32 - __builtin_clz(s-1) : 0, n = 1 << L;
	a.resize(n), b.resize(n);
	fft(a, n);
	fft(b, n);
	num d = inv(num(n));
	rep(i,0,n) a[i] = a[i] * b[i] * d;
	reverse(a.begin()+1, a.end());
	fft(a, n);
	a.resize(s);
	return a;
} /// end-hash

// Complex/NTT power-series inverse
// Doubles b as b[:n] = (2 - a[:n] * b[:n/2]) * b[:n/2]
vn inverse(const vn& a) { /// start-hash
	if (a.empty()) return {};
	vn b({inv(a[0])});
	b.reserve(2*a.size());
	while (sz(b) < sz(a)) {
		int n = 2*sz(b);
		b.resize(2*n, 0);
		if (sz(fa) < 2*n) fa.resize(2*n);
		fill(fa.begin(), fa.begin()+2*n, 0);
		copy(a.begin(), a.begin()+min(n,sz(a)), fa.begin());
		fft(b, 2*n);
		fft(fa, 2*n);
		num d = inv(num(2*n));
		rep(i, 0, 2*n) b[i] = b[i] * (2 - fa[i] * b[i]) * d;
		reverse(b.begin()+1, b.end());
		fft(b, 2*n);
		b.resize(n);
	}
	b.resize(a.size());
	return b;
} /// end-hash

#if FFT
// Double multiply (num = complex)
using vd = vector<double>;
vd multiply(const vd& a, const vd& b) { /// start-hash
	int s = sz(a) + sz(b) - 1;
	if (s <= 0) return {};
	int L = s > 1 ? 32 - __builtin_clz(s-1) : 0, n = 1 << L;
	if (sz(fa) < n) fa.resize(n);
	if (sz(fb) < n) fb.resize(n);

	fill(fa.begin(), fa.begin() + n, 0);
	rep(i,0,sz(a)) fa[i].x = a[i];
	rep(i,0,sz(b)) fa[i].y = b[i];
	fft(fa, n);
	trav(x, fa) x = x * x;
	rep(i,0,n) fb[i] = fa[(n-i)&(n-1)] - conj(fa[i]);
	fft(fb, n);
	vd r(s);
	rep(i,0,s) r[i] = fb[i].y / (4*n);
	return r;
} /// end-hash

// Integer multiply mod m (num = complex) /// start-hash
vector<long long> multiply(const vi& a, const vi& b) {
	int s = sz(a) + sz(b) - 1;
	if (s <= 0) return {};
	int L = s > 1 ? 32 - __builtin_clz(s-1) : 0, n = 1 << L;
	if (sz(fa) < n) fa.resize(n);
	if (sz(fb) < n) fb.resize(n);

	rep(i,0,sz(a)) fa[i] = num(a[i] & ((1<<15)-1), a[i] >> 15);
	fill(fa.begin()+sz(a), fa.begin() + n, 0);
	rep(i,0,sz(b)) fb[i] = num(b[i] & ((1<<15)-1), b[i] >> 15);
	fill(fb.begin()+sz(b), fb.begin() + n, 0);

	fft(fa, n);
	fft(fb, n);
	double r0 = 0.5 / n; // 1/2n
	rep(i,0,n/2+1) {
		int j = (n-i)&(n-1);
		num g0 = (fb[i] + conj(fb[j])) * r0;
		num g1 = (fb[i] - conj(fb[j])) * r0;
		swap(g1.x, g1.y); g1.y *= -1;
		if (j != i) {
			swap(fa[j], fa[i]);
			fb[j] = fa[j] * g1;
			fa[j] = fa[j] * g0;
		}
		fb[i] = fa[i] * conj(g1);
		fa[i] = fa[i] * conj(g0);
	}
	fft(fa, n);
	fft(fb, n);
	vector<long long> r(s);
	rep(i,0,s) r[i] = int((ll(fa[i].x+0.5)
				+ (ll(fa[i].y+0.5) * (1 << 15))
				+ (ll(fb[i].x+0.5) * (1 << 15))
				+ (ll(fb[i].y+0.5) * (1 << 30))));
	return r;
} /// end-hash
#endif

} // namespace fft

int main() {
	using namespace std;
	ios_base::sync_with_stdio(false), cin.tie(nullptr);
	array<int, 2> N; int Q; cin >> N[0] >> N[1] >> Q;
	array<vector<pair<int, int>>, 2> A;
	for (int z = 0; z < 2; z++) {
		A[z].resize(N[z]+2);
		for (int i = 1; i <= N[z]; i++) {
			cin >> A[z][i].first; A[z][i].second = i;
		}
	}
	vector<int> queries(Q); for (auto& q : queries) cin >> q;

	const int X = int(1e5) + 100;
	vector<long long> ans(2 * X - 1);

	for (int round = 0; round < 2; round++) {
		const int INF = 1e9;
		array<vector<double>, 2> mults;
		for (int z = 0; z < 2; z++) {
			mults[z].assign(X, 0);

			A[z][0].first = A[z][N[z]+1].first = round ? INF : -INF;
			for (int i = 1; i <= N[z]; i++) {
				if (A[z][i] < A[z][i-1] && A[z][i] < A[z][i+1]) {
					mults[z][A[z][i].first]--;
				} else if (A[z][i] > A[z][i-1] && A[z][i] > A[z][i+1]) {
					mults[z][A[z][i].first]++;
				}
			}
		}
		vector<double> cur_res = fft::multiply(mults[0], mults[1]);
		for (int i = 0; i < 2 * X - 1; i++) {
			long long v = ((cur_res[i] > 0) - (cur_res[i] < 0)) * (long long)(abs(cur_res[i]) + 0.5);
			ans[i] += v;
		}
	}
	for (int i = 2 * X - 3; i >= 0; i--) {
		ans[i] += ans[i+1];
	}
	long long tot = ans[0];
	for (auto& a : ans) a = (2 * a - tot) / 2;
	for (int q : queries) {
		cout << ans[q] << '\n';
	}

	return 0;
}

// we can handle the 1good 2bad by wrapping in a white/back ring and adding the 2

// Each cc can be uniquely identified by a max-row max-col cross such that neither can reach further
//
// Conjecture: the blockers match


#include <cstdio>
#include <cmath>
#include <complex>
#include <algorithm>

using ld = long double;
using cd = std::complex<ld>;
using ll = long long;

const ld PI = 4*atan((ld)1);
const int MN = 1e5+10;
const int MV = 1 << 18;
cd rou[MV];

template<bool inv=0>
void fft(cd *a, int L)
{
	for(int i=0,j;i<1<<L;++i)
	{
		j=0;
		for(int k=0;k<L;++k)
			if(i>>k&1) j|=1<<L-k-1;
		if(i<j) std::swap(a[i], a[j]);
	}
	for(int i=0;i<1<<L;++i)
	{
		ld ang=2*PI*i/(1<<L);
		if(inv) ang*=-1;
		rou[i]={cos(ang), sin(ang)};
	}
	for(int l=0;l<L;++l)
		for(int i=0;i<1<<L;i+=1<<l+1)
			for(int j=0;j<1<<l;++j)
			{
				cd d=a[i|1<<l|j]*rou[j<<L-l-1];
				a[i|1<<l|j]=a[i|j]-d;
				a[i|j]+=d;
			}
	if(inv)
		for(int i=0;i<1<<L;++i) a[i]/=1<<L;
}

const int L = 4;
int N, M, Q, a[MN], b[MN];
ll f[MV], ctr;
cd p[MV], q[MV];

void mul()
{
	fft(p, L);
	fft(q, L);
	for(int i=0;i<1<<L;++i) p[i]*=q[i];
	fft<1>(p, L);
}
void res()
{
	memset(p, 0, sizeof*p<<L);
	memset(q, 0, sizeof*q<<L);
}

int main()
{
	scanf("%d%d%d", &N, &M, &Q);
	for(int i=0;i<N;++i) scanf("%d", a+i);
	for(int i=0;i<M;++i) scanf("%d", b+i);

	//V
	for(int i=0;i<N;++i) p[a[i]] += cd{1,0};
	for(int i=0;i<M;++i) q[b[i]] += cd{1,0};
	mul();
	for(int i=0;i+1<1<<L;++i) f[i+1] -= ctr += (ll)round(p[i].real()); ctr=0;
	for(int i=(1<<L)-1;i>=0;--i) f[i] += ctr += (ll)round(p[i].real()); ctr=0;
	res();

	//HOT
	//Q
	for(int i=1;i<N;++i) p[std::max(a[i], a[i-1])] += cd{1,0};
	for(int i=1;i<M;++i) q[std::max(b[i], b[i-1])] += cd{1,0};
	mul();
	for(int i=(1<<L)-1;i>=0;--i) f[i] += ctr += (ll)round(p[i].real()); ctr=0;
	res();

	//E, one direction
	for(int i=1;i<N;++i) p[std::max(a[i], a[i-1])] += cd{1,0};
	for(int i=0;i<M;++i) q[b[i]] += cd{1,0};
	mul();
	for(int i=(1<<L)-1;i>=0;--i) f[i] -= ctr += (ll)round(p[i].real()); ctr=0;
	res();

	//E, other direction
	for(int i=0;i<N;++i) p[a[i]] += cd{1,0};
	for(int i=1;i<M;++i) q[std::max(b[i], b[i-1])] += cd{1,0};
	mul();
	for(int i=(1<<L)-1;i>=0;--i) f[i] -= ctr += (ll)round(p[i].real()); ctr=0;
	res();

	//COLD
	//Q
	for(int i=1;i<N;++i) p[std::min(a[i], a[i-1])] += cd{1,0};
	for(int i=1;i<M;++i) q[std::min(b[i], b[i-1])] += cd{1,0};
	mul();
	for(int i=0;i+1<1<<L;++i) f[i+1] -= ctr += (ll)round(p[i].real()); ctr=0;
	res();

	//E, one direction
	for(int i=1;i<N;++i) p[std::min(a[i], a[i-1])] += cd{1,0};
	for(int i=0;i<M;++i) q[b[i]] += cd{1,0};
	mul();
	for(int i=0;i+1<1<<L;++i) f[i+1] += ctr += (ll)round(p[i].real()); ctr=0;
	res();

	//E, other direction
	for(int i=0;i<N;++i) p[a[i]] += cd{1,0};
	for(int i=1;i<M;++i) q[std::min(b[i], b[i-1])] += cd{1,0};
	mul();
	for(int i=0;i+1<1<<L;++i) f[i+1] += ctr += (ll)round(p[i].real()); ctr=0;
	res();

	for(int i=0,x;i<Q;++i)
	{
		scanf("%d", &x);
		printf("%lld\n", f[x]);
	}
	return 0;
}


#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int N = 600000+10;
const double PI = acos(-1);
struct Complex {
    double x, y;
    Complex(double x=0.0, double y=0.0) : x(x), y(y) {}
    Complex operator + (const Complex &b) const {
        return Complex(x+b.x, y+b.y);
    }
    Complex operator - (const Complex &b) const {
        return Complex(x-b.x, y-b.y);
    }
    Complex operator * (const Complex &b) const{
        return Complex(x * b.x - y * b.y, x * b.y + y * b.x);
    }
} x1[N<<2], x2[N<<2];
void change(Complex y[], int len) {
    for(int i=1,j=len/2;i<len-1;i++){
        if(i<j) swap(y[i], y[j]);
        int k=len/2;
        while (j>=k) {
            j-=k; k/=2;
        }
        if(j<k) j+=k;
    }
}
void fft(Complex y[], int len, int on){
    change(y, len);
    for(int h=2;h<=len;h<<=1) {
        Complex wn(cos(-on*2*PI/h), sin(-on*2*PI/h));
        for(int j=0;j<len;j+=h){
            Complex w(1,0);
            for(int k=j;k<j+h/2;k++) {
                Complex u=y[k];
                Complex t=w*y[k+h/2];
                y[k]=u+t;
                y[k+h/2]=u-t;
                w=w*wn;
            }
        }
    }
    if (on==-1) for(int i=0;i<len;i++) y[i].x /= len;
}
void mul(LL *p, int& dp, LL* q, int& dq) {
    int len=1;
    while(len<=dp+dq) len<<=1;
    for(int i=0;i<dp;i++) x1[i]=Complex(p[i],0);
    for(int i=dp;i<len;i++) x1[i]=Complex(0,0);
    for(int i=0;i<dq;i++) x2[i]=Complex(q[i],0);
    for(int i=dq;i<len;i++) x2[i]=Complex(0,0);
    fft(x1,len,1);
    fft(x2,len,1);
    for(int i=0;i<len;i++) {
        x1[i]=x1[i]*x2[i];
    }
    fft(x1,len,-1);
    for(int i=0;i<=200002;i++){
        //printf("%.4f\n", x1[i].x);
        p[i]=round(x1[i]);
    }
    dp+=dq;
}

LL n,m;int q;

int a[N],b[N];
namespace Min{
    LL f[N<<1],g[N<<1];
    LL s1[N], s2[N], s3[N];
    void gen1() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++) f[a[i]] ++;
        for(int i=1;i<m;i++) g[min(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq); s1[0]=0;
        for(int i=1;i<=200000;i++) s1[i]=s1[i-1]+f[i];
    }
    void gen2() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[min(a[i],a[i+1])] ++;
        for(int i=1;i<=m;i++) g[b[i]] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq); s2[0]=0;
        for(int i=1;i<=200000;i++) s2[i]=s2[i-1]+f[i];
    }
    void gen3() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[min(a[i],a[i+1])] ++;
        for(int i=1;i<m;i++) g[min(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq); s3[0]=0;
        for(int i=1;i<=200000;i++) s3[i]=s3[i-1]+f[i];
    }
}
namespace Max{
    LL f[N<<1],g[N<<1];
    LL s1[N], s2[N], s3[N], s4[N];
    void gen1() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++) f[a[i]] ++;
        for(int i=1;i<m;i++) g[max(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq);
        s1[0]=0;
        for(int i=1;i<=200000;i++) s1[i]=s1[i-1]+f[i];
    }
    void gen2() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[max(a[i],a[i+1])] ++;
        for(int i=1;i<=m;i++) g[b[i]] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq);
        s2[0]=0;
        for(int i=1;i<=200000;i++) s2[i]=s2[i-1]+f[i];
    }
    void gen3() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[max(a[i],a[i+1])] ++;
        for(int i=1;i<m;i++) g[max(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
    /*
    printf("f\n");
        for(int i=0;i<7;i++) printf("%d ", f[i]); printf("\n");
    printf("g\n");
        for(int i=0;i<7;i++) printf("%d ", g[i]); printf("\n");
    */
        mul(f,dp,g,dq);
    //printf("m\n");
        //for(int i=0;i<7;i++) printf("%d ", f[i]); printf("\n");
        s3[0]=0;
        for(int i=1;i<=200000;i++) s3[i]=s3[i-1]+f[i];
    }
    void gen4() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++) f[a[i]] ++;
        for(int i=1;i<=m;i++) g[b[i]] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq);
        s4[0]=0;
        for(int i=1;i<=200000;i++) s4[i]=s4[i-1]+f[i];
    }
}

int main() {
    scanf("%lld%lld%d", &n,&m,&q);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
    }
    for(int i=1;i<=m;i++){
        scanf("%d",&b[i]);
    }
    Min::gen1(); Min::gen2(); Min::gen3();
    Max::gen1(); Max::gen2(); Max::gen3(); Max::gen4();
    //printf("# %d\n", Max::s3[4]);
    while(q--) {
        int x; scanf("%d",&x);
        LL ans1 = (1LL*n*(m-1) - Min::s1[x-1]) + (1LL*(n-1)*m - Min::s2[x-1]) - (1LL*n*m - Max::s4[x-1]) - (1LL*(n-1)*(m-1) - Min::s3[x-1]);
        LL ans2 = Max::s1[x-1] + Max::s2[x-1] - Max::s4[x-1] - Max::s3[x-1];
        printf("%lld\n", ans2-ans1);
    }
}


#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
typedef long long LL;
const int N = 600000+10;
const double PI = acos(-1);
struct Complex {
    double x, y;
    Complex(double x=0.0, double y=0.0) : x(x), y(y) {}
    Complex operator + (const Complex &b) const {
        return Complex(x+b.x, y+b.y);
    }
    Complex operator - (const Complex &b) const {
        return Complex(x-b.x, y-b.y);
    }
    Complex operator * (const Complex &b) const{
        return Complex(x * b.x - y * b.y, x * b.y + y * b.x);
    }
} x1[N<<2], x2[N<<2];
void change(Complex y[], int len) {
    for(int i=1,j=len/2;i<len-1;i++){
        if(i<j) swap(y[i], y[j]);
        int k=len/2;
        while (j>=k) {
            j-=k; k/=2;
        }
        if(j<k) j+=k;
    }
}
void fft(Complex y[], int len, int on){
    change(y, len);
    for(int h=2;h<=len;h<<=1) {
        Complex wn(cos(-on*2*PI/h), sin(-on*2*PI/h));
        for(int j=0;j<len;j+=h){
            Complex w(1,0);
            for(int k=j;k<j+h/2;k++) {
                Complex u=y[k];
                Complex t=w*y[k+h/2];
                y[k]=u+t;
                y[k+h/2]=u-t;
                w=w*wn;
            }
        }
    }
    if (on==-1) for(int i=0;i<len;i++) y[i].x /= len;
}
void mul(LL *p, int& dp, LL* q, int& dq) {
    int len=1;
    while(len<=dp+dq) len<<=1;
    for(int i=0;i<dp;i++) x1[i]=Complex(p[i],0);
    for(int i=dp;i<len;i++) x1[i]=Complex(0,0);
    for(int i=0;i<dq;i++) x2[i]=Complex(q[i],0);
    for(int i=dq;i<len;i++) x2[i]=Complex(0,0);
    fft(x1,len,1);
    fft(x2,len,1);
    for(int i=0;i<len;i++) {
        x1[i]=x1[i]*x2[i];
    }
    fft(x1,len,-1);
    for(int i=0;i<=200002;i++){
        //printf("%.4f\n", x1[i].x);
        p[i]=(LL)(x1[i].x+0.1);
    }
    dp+=dq;
}

LL n,m;int q;

int a[N],b[N];
namespace Min{
    LL f[N<<1],g[N<<1];
    LL s1[N], s2[N], s3[N];
    void gen1() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++) f[a[i]] ++;
        for(int i=1;i<m;i++) g[min(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq); s1[0]=0;
        for(int i=1;i<=200000;i++) s1[i]=s1[i-1]+f[i];
    }
    void gen2() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[min(a[i],a[i+1])] ++;
        for(int i=1;i<=m;i++) g[b[i]] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq); s2[0]=0;
        for(int i=1;i<=200000;i++) s2[i]=s2[i-1]+f[i];
    }
    void gen3() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[min(a[i],a[i+1])] ++;
        for(int i=1;i<m;i++) g[min(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq); s3[0]=0;
        for(int i=1;i<=200000;i++) s3[i]=s3[i-1]+f[i];
    }
}
namespace Max{
    LL f[N<<1],g[N<<1];
    LL s1[N], s2[N], s3[N], s4[N];
    void gen1() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++) f[a[i]] ++;
        for(int i=1;i<m;i++) g[max(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq);
        s1[0]=0;
        for(int i=1;i<=200000;i++) s1[i]=s1[i-1]+f[i];
    }
    void gen2() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[max(a[i],a[i+1])] ++;
        for(int i=1;i<=m;i++) g[b[i]] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq);
        s2[0]=0;
        for(int i=1;i<=200000;i++) s2[i]=s2[i-1]+f[i];
    }
    void gen3() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<n;i++) f[max(a[i],a[i+1])] ++;
        for(int i=1;i<m;i++) g[max(b[i],b[i+1])] ++;
        int dp=100000,dq=100000;
    /*
    printf("f\n");
        for(int i=0;i<7;i++) printf("%d ", f[i]); printf("\n");
    printf("g\n");
        for(int i=0;i<7;i++) printf("%d ", g[i]); printf("\n");
    */
        mul(f,dp,g,dq);
    //printf("m\n");
        //for(int i=0;i<7;i++) printf("%d ", f[i]); printf("\n");
        s3[i]=0;
        for(int i=1;i<=200000;i++) s3[i]=s3[i-1]+f[i];
    }
    void gen4() {
        memset(f,0,sizeof(f)); memset(g,0,sizeof(g));
        for(int i=1;i<=n;i++) f[a[i]] ++;
        for(int i=1;i<=m;i++) g[b[i]] ++;
        int dp=100000,dq=100000;
        mul(f,dp,g,dq);
        s4[i]=0;
        for(int i=1;i<=200000;i++) s4[i]=s4[i-1]+f[i];
    }
}

int main() {
    scanf("%lld%lld%d", &n,&m,&q);
    for(int i=1;i<=n;i++){
        scanf("%d",&a[i]);
       // a[i]=rand()%100000+1;
    }
    for(int i=1;i<=m;i++){
        scanf("%d",&b[i]);
        //b[i]=rand()%100000+1;
    }
        /*
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            printf("%d ", a[i]+b[j]);
        }
        printf("\n");
    }
    */
    Min::gen1(); Min::gen2(); Min::gen3();
    Max::gen1(); Max::gen2(); Max::gen3(); Max::gen4();
    //printf("# %d\n", Max::s3[4]);
    while(q--) {
        int x; scanf("%d",&x);
        LL ans1 = (1LL*n*(m-1) - Min::s1[x-1]) + (1LL*(n-1)*m - Min::s2[x-1]) - (1LL*n*m - Max::s4[x-1]) - (1LL*(n-1)*(m-1) - Min::s3[x-1]);
        LL ans2 = Max::s1[x-1] + Max::s2[x-1] - Max::s4[x-1] - Max::s3[x-1];
        printf("%lld\n", ans2-ans1);
    }
}


#include <bits/stdc++.h>

using namespace std;

vector<int> mem[5001];

vector<int> Fact(int x) {
    if (!mem[x].empty()) {
        return mem[x];
    }

    vector<int> res;
    for (int i = 2; i * i <= x; ++i) {
        while (x % i == 0) {
            res.push_back(i);
            x /= i;
        }
    }
    if (x > 1) {
        res.push_back(x);
    }

    return mem[x] = res;
}

vector<int> F(int x) {
    vector<int> res;
    for (int i = 2; i <= x; ++i) {
        auto f = Fact(i);
        res.insert(res.end(), f.begin(), f.end());
    }
    sort(res.begin(), res.end());
    reverse(res.begin(), res.end());

    return res;
}

vector<int> cnt(1);
vector<unordered_map<int, int>> nxt(1);

int64_t ans = 0;

void Add(const vector<int>& data, int delta) {
    int v = 0;
    ans += 1LL * data.size() * delta;
    for (int x : data) {
        if (!nxt[v].count(x)) {
            nxt[v][x] = nxt.size();
            nxt.emplace_back();
            cnt.emplace_back();
        }
        v = nxt[v][x];
        cnt[v] += delta;
    }
}

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

    int n;
    cin >> n;
    vector<int> cnt(5001);
    for (int i = 0; i < n; ++i) {
        int k;
        cin >> k;
        ++cnt[k];
    }

    for (size_t i = 0; i < cnt.size(); ++i) {
        Add(F(i), cnt[i]);
    }

    int v = 0;
    for (bool flag = false; flag; flag = false) {
        for (auto x : nxt[v]) {
            if (cnt[x.second] > n - cnt[x.second]) {
                ans -= cnt[x.second];
                ans += n - cnt[x.second];
                v = x.second;
                flag = true;
                break;
            }
        }
    }

    cout << ans << endl;

    return 0;
}


#include <bits/stdc++.h>

using namespace std;

int n, k = 5000;
int d[5050], cnt[5050]m id[5050];
vector<int> pr;
int fac[5050][1010], s[5050][1010];

void sieve(void) {
  for (int i = 2; i <= k; i++) {
    if (!d[i]) {
      id[i] = (int) pr.size();
      pr.push_back(i);
      for (int j = i; j <= k; j++) {
        if (!d[j]) d[j] = i;
      }
    }
  }
  for (int i = 1; i <= k; i++) {
    for (int j = 0; j < (int) pr.size(); j++) {
      fac[i][j] = fac[i - 1][j];
    }
    int tmp = i;
    while (tmp > 1) {
      int t = d[tmp];
      fac[i][id[t]]++;
      tmp /= t;
    }
    for (int j = 0; j < (int) pr.size(); j++) {
      s[i][j] = fac[i][j] + s[i][j - 1];
    }
  }
}

int f[1010];

void solve(void) {
  long long ans = 0;
  int rem = 0;
  for (int i = 0; i < (int) pr.size(); i++) rem += f[i];
  vector<int> cand(k, 0);
  iota(cand.begin(), cand.end(), 1);

  int l = 1, r = k;
  for (int i = (int) pr.size() - 1; i >= 0; i--) {
    rem -= f[i];
    while (l <= r && fac[l][i] < f[i]) {
      ans += 1ll * cnt[l] * (rem + (i ? s[l][i - 1] : 0) + abs(fac[l][i] - f[i]));
      l++;
    }
    while (r >= l && fac[r][i] > f[i]) {
      ans += 1ll * cnt[r] * (rem + (i ? s[r][i - 1] : 0) + abs(fac[r][i] - f[i]));
      r--;
    }
  }

  return ans;
}

int main() {
  ios::sync_with_stdio(0); cin.tie(0);

  cin >> n;
  int x;
  for (int i = 1; i <= n; i++) {
    cin >> x;
    if (x == 0) x = 1;
    cnt[x]++;
  }
  sieve();
  long long ans = 1e18;
  for (int i = 1; i <= k; i++) {
    for (int j = 0; j < (int) pr.size(); j++) f[j] = fac[i][j];
    ans = min(ans, solve());
  }
  for (int i = 1; i < k; i++) {
    int flg = 0;
    for (int j = (int) pr.size() - 1; j >= 0; j--) {
      if (flg) f[j] = 0;
      else if (fac[i][j] != fac[i + 1][j]) {
        flg = 1;
        f[j] = min(fac[i][j], fac[i + 1][j]);
      }
      else f[j] = fac[i][j];
    }
    ans = min(ans, solve());
  }

  cout << ans << '\n';
}


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

typedef long long LL;

const int N=5000,M=1000;

int n,cnt[N+9];

void into(){
  scanf("%d",&n);
  for (int i=1;i<=n;++i){
	int x;
	scanf("%d",&x);
	++cnt[x?x:1];
  }
}

int b[N+9],pr[M+9],cp;
int c[N+9][M+9];

void Sieve(){
  for (int i=2;i<=N;++i){
	if (!b[i]) pr[++cp]=i,c[i][cp]=c[i][0]=1;
	for (int j=1;j<=cp&&i*pr[j]<=N;++j){
	  int t=i*pr[j];
	  b[t]=1;
	  c[t][0]=c[i][0]+1;
	  for (int k=1;k<=cp;++k) c[t][k]=c[i][k];
	  ++c[t][j];
	  if (i%pr[j]==0) break;
	}
  }
  for (int i=1;i<=N;++i)
	for (int j=0;j<=cp;++j) c[i][j]+=c[i-1][j];
}

int ht[M+9];
int a[N+9],ca;
int now[M+9];

void Get_ht(){
  for (int i=1;i<=N;++i)
	if (cnt[i]) a[++ca]=i;
  for (int id=cp+1,ct=0;2333;){
	for (int i=1;i<=cp;++i) now[i]=0;
	for (int i=1;i<=ca;++i){
	  int t=a[i];
	  if (c[t][id]>ct) now[id]+=cnt[t];
	  else
	    for (int j=id-1;j>=1;--j)
		  if (c[t][j]) {now[j]+=cnt[t];break;}
	}
	int p=0;
	for (int i=1;i<=cp;++i)
	  if (now[i]>n>>1) {p=i;break;}
	if (!p) break;
    for (int lst=0,i=1;i<=ca;++i){
	  int t=a[i],tmp=0;
	  if (c[t][id]>ct) tmp=id;
	  else
	    for (int j=id-1;j>=1;--j)
		  if (c[t][j]) {tmp=j;break;}
	  if (tmp==p) a[++lst]=t;
	}
	ct=id==p?ct+1:1;
	++ht[id=p];++ht[0];
	ca=lst;
  }
}

LL ans;

void Get_ans(){
  for (int i=1;i<=N;++i){
	if (!cnt[i]) continue;
	int sum=ht[0]+c[i][0];
	for (int j=cp;j>=1;--j)
	  if (ht[j]^c[i][j]){
		ans+=(LL)cnt[i]*(sum-2*min(ht[j],c[i][j]));
		break;
	  }else sum-=ht[j]+c[i][j];
  }
}

void work(){
  Sieve();
  Get_ht();
  Get_ans();
}

void outo(){
  printf("%lld\n",ans);
}

int main(){
  into();
  work();
  outo();
  return 0;
}