#include <bits/stdc++.h>

#define inf 0x3f3f3f3f

#define INF 0x3f3f3f3f3f3f3f3fLL

#define MOD 1000000007

#define pb push_back

#define sq(x) ((x)*(x))

#define x first

#define y second

#define eps 1e-9

#define bpt(x) (__builtin_popcount(x))

#define bptl(x) (__builtin_popcountll(x))

#define bit(x, y) (((x)>>(y))&1)

#define bclz(x) (__builtin_clz(x))

#define bclzl(x) (__builtin_clzll(x))

#define bctz(x) (__builtin_ctz(x))

#define bctzl(x) (__builtin_ctzll(x))

#define SZ(x) ((x).size())

using namespace std;

typedef long long INT;

typedef vector<int> VI;

typedef pair<int, int> pii;

typedef pair<pii, int> pi3;

typedef double DO;

template<typename T, typename U> inline void smin(T &a, const U &b) {if (a>b) a=b;}

template<typename T, typename U> inline void smax(T &a, const U &b) {if (a<b) a=b;}

#define INPUT_LEN 1000

#define gets my_gets

char gchar() {static char tbuf1[INPUT_LEN],*tmp_st=tbuf1,*tmp_ed=tbuf1;if(tmp_st==tmp_ed){int len=fread(tbuf1,1,INPUT_LEN,stdin);if (len==0)return -1;tmp_ed=tbuf1+len;tmp_st=tbuf1;}return*(tmp_st++);}

inline bool gn(int &x) {char c, sg=0;while (c=gchar(),(c>'9'||c<'0')&&c!='-'&&c!=-1);if (c==-1) return 0;for((c=='-'?sg=1,c=gchar():0),x=0;c>='0'&&c<='9';c=gchar())x=(x<<1)+(x<<3)+c-'0';if (sg) x=-x;return 1;}

inline bool gn(INT &x) {char c, sg=0;while (c=gchar(),(c>'9'||c<'0')&&c!='-'&&c!=-1);if (c==-1) return 0;for((c=='-'?sg=1,c=gchar():0),x=0;c>='0'&&c<='9';c=gchar())x=(x<<1)+(x<<3)+c-'0';if (sg) x=-x;return 1;}

inline bool gn(char &x) {while(x=gchar(),x!=-1&&isspace(x));return x!=-1;}

inline bool gn(string &s){char c;s.clear();while(c=gchar(),c!=-1&&isspace(c));if(c!=-1)s+=c;while(c=gchar(),c!=-1&&!isspace(c))s+=c;return c!=-1;}

inline bool gn(DO &x) {string s;bool ok=gn(s);x=atof(s.c_str());return ok;}

inline bool gn(char *s) {string s1;bool ok=gn(s1);strcpy(s,s1.c_str());return ok;}

inline bool gets(char *s) {char c,t=0;while(c=gchar(),c!=-1&&c!='\n')*s++=c,t=1;*s=0;return c!=-1 || t;};

inline void print(int x) {if(x<0){putchar('-');return print(-x);}if(x<10){putchar('0'+x);return;}print(x/10);putchar(x%10+'0');}

inline void print(INT x) {if(x<0){putchar('-');return print(-x);}if(x<10){putchar('0'+x);return;}print(x/10);putchar(x%10+'0');}

inline bool print(char &x) {putchar(x);}

inline void print(DO &x){printf("%.10lf", x);}

inline void print(char *s){printf("%s", s);}

inline void print(string &s){printf("%s", s.c_str());}

template<class T,class T1>inline bool gn(T &x, T1 &y) {bool ok=gn(x); gn(y);return ok;}

template<class T,class T1,class T2>inline bool gn(T &x, T1 &y, T2 &z){bool ok=gn(x); gn(y); gn(z);return ok;}

template<class U,class V,class W,class X>inline bool gn(U &u, V &v, W &w, X &x){bool ok=gn(u,v);gn(w,x);return ok;}

template<class T>inline void printsp(T x) {print(x);putchar(' ');}

template<class T>inline void println(T x) {print(x);putchar('\n');}

template<class T,class U>inline void print(T x, U y){printsp(x);println(y);}

template<class T,class U,class V>inline void print(T x, U y, V z){printsp(x);print(y,z);}

template<class T,class U,class V,class W>inline void print(T x, U y, V z,W w){printsp(x);print(y, z, w);}

int power(int a, int b, int m, int ans=1) {

	for (; b; b>>=1, a=1LL*a*a%m) if (b&1) ans=1LL*ans*a%m;

	return ans;

}

int n,d[1000];

int main() {

#ifndef ONLINE_JUDGE

	freopen("in.in", "r", stdin);

	freopen("out.out", "w", stdout);

#endif

	scanf("%d", &n);

	for(int i=0;i<n;i++){

		scanf("%d", &d[i]);

	}

	int p=n-1, q=0;

	for(int i=n-1; i>=0; i--){

		if(d[i]>=d[p])	p=i;

	}

	for(int i=0;i<n;i++){

		if(d[i]<=d[q])	q=i;

	}

	if(p==q)	printf("%d\n", 0);

	if(p>q)		printf("%d\n", p+n-q-2);

	if(p<q)		printf("%d\n", p+n-q-1);

	return 0;

}


#include <bits/stdc++.h>

#define inf 0x3f3f3f3f

#define INF 0x3f3f3f3f3f3f3f3fLL

#define MOD 1000000007

#define pb push_back

#define sq(x) ((x)*(x))

#define x first

#define y second

#define eps 1e-9

#define bpt(x) (__builtin_popcount(x))

#define bptl(x) (__builtin_popcountll(x))

#define bit(x, y) (((x)>>(y))&1)

#define bclz(x) (__builtin_clz(x))

#define bclzl(x) (__builtin_clzll(x))

#define bctz(x) (__builtin_ctz(x))

#define bctzl(x) (__builtin_ctzll(x))

#define SZ(x) ((x).size())

using namespace std;

typedef long long INT;

typedef vector<int> VI;

typedef pair<int, int> pii;

typedef pair<pii, int> pi3;

typedef double DO;

template<typename T, typename U> inline void smin(T &a, const U &b) {if (a>b) a=b;}

template<typename T, typename U> inline void smax(T &a, const U &b) {if (a<b) a=b;}

#define INPUT_LEN 1000

#define gets my_gets

char gchar() {static char tbuf1[INPUT_LEN],*tmp_st=tbuf1,*tmp_ed=tbuf1;if(tmp_st==tmp_ed){int len=fread(tbuf1,1,INPUT_LEN,stdin);if (len==0)return -1;tmp_ed=tbuf1+len;tmp_st=tbuf1;}return*(tmp_st++);}

inline bool gn(int &x) {char c, sg=0;while (c=gchar(),(c>'9'||c<'0')&&c!='-'&&c!=-1);if (c==-1) return 0;for((c=='-'?sg=1,c=gchar():0),x=0;c>='0'&&c<='9';c=gchar())x=(x<<1)+(x<<3)+c-'0';if (sg) x=-x;return 1;}

inline bool gn(INT &x) {char c, sg=0;while (c=gchar(),(c>'9'||c<'0')&&c!='-'&&c!=-1);if (c==-1) return 0;for((c=='-'?sg=1,c=gchar():0),x=0;c>='0'&&c<='9';c=gchar())x=(x<<1)+(x<<3)+c-'0';if (sg) x=-x;return 1;}

inline bool gn(char &x) {while(x=gchar(),x!=-1&&isspace(x));return x!=-1;}

inline bool gn(string &s){char c;s.clear();while(c=gchar(),c!=-1&&isspace(c));if(c!=-1)s+=c;while(c=gchar(),c!=-1&&!isspace(c))s+=c;return c!=-1;}

inline bool gn(DO &x) {string s;bool ok=gn(s);x=atof(s.c_str());return ok;}

inline bool gn(char *s) {string s1;bool ok=gn(s1);strcpy(s,s1.c_str());return ok;}

inline bool gets(char *s) {char c,t=0;while(c=gchar(),c!=-1&&c!='\n')*s++=c,t=1;*s=0;return c!=-1 || t;};

inline void print(int x) {if(x<0){putchar('-');return print(-x);}if(x<10){putchar('0'+x);return;}print(x/10);putchar(x%10+'0');}

inline void print(INT x) {if(x<0){putchar('-');return print(-x);}if(x<10){putchar('0'+x);return;}print(x/10);putchar(x%10+'0');}

inline bool print(char &x) {putchar(x);}

inline void print(DO &x){printf("%.10lf", x);}

inline void print(char *s){printf("%s", s);}

inline void print(string &s){printf("%s", s.c_str());}

template<class T,class T1>inline bool gn(T &x, T1 &y) {bool ok=gn(x); gn(y);return ok;}

template<class T,class T1,class T2>inline bool gn(T &x, T1 &y, T2 &z){bool ok=gn(x); gn(y); gn(z);return ok;}

template<class U,class V,class W,class X>inline bool gn(U &u, V &v, W &w, X &x){bool ok=gn(u,v);gn(w,x);return ok;}

template<class T>inline void printsp(T x) {print(x);putchar(' ');}

template<class T>inline void println(T x) {print(x);putchar('\n');}

template<class T,class U>inline void print(T x, U y){printsp(x);println(y);}

template<class T,class U,class V>inline void print(T x, U y, V z){printsp(x);print(y,z);}

template<class T,class U,class V,class W>inline void print(T x, U y, V z,W w){printsp(x);print(y, z, w);}

int power(int a, int b, int m, int ans=1) {

	for (; b; b>>=1, a=1LL*a*a%m) if (b&1) ans=1LL*ans*a%m;

	return ans;

}

int main() {

#ifndef ONLINE_JUDGE

	freopen("in.in", "r", stdin);

	freopen("out.out", "w", stdout);

#endif

	int n,d[10000];

	scanf("%d", &n);

	for(int i=0;i<n;i++){

		scanf("%d", &d[i]);

	}

	int p=n-1, q=0;

	for(int i=n-1;i>=0;i--){

		if(d[i]>=d[p])	p=i;

	}

	for(int i=0;i<n-1;i++){

		if(d[i]<=d[q])	q=i;

	}

	if(p==q)	printf("%d", 0);

	if(p>q)		printf("%d", p+n-q-2);

	if(p<q)		printf("%d", p+n-q-1);

	return 0;

}


#include<bits/stdc++.h>
using namespace std;
int maxx,n,minn=205,a,ax,in;
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a;
		if(a>maxx) ax=i,maxx=a;
		if(a<=minn) in=i,minn=a;
	}
	if(ax>in) cout<<ax+n-in-2;
	else cout<<ax+n-in-1;
	return 0;
}


#include<iostream>
#define INS 1000000000
using namespace std;
int main(void)
{
	int n, min = INS, max = -INS, k, minw, maxw, ans;
	cin>>n;
	for(int i = 1; i <= n; i++)
	{
		cin>>k;
		if (min >= k) min=k, minw=i;
		if (max <= k) max=k, maxw=i;
	}
	ans=maxw-1+n-minw;
	cout<<((minw < maxw) ? ans-1 : ans);
	return 0;
}


#include <cstdio>
const int maxn = 110;
int a[maxn];

int main() {
	int cntn, cntm;
	int n, minn = 110, maxx = 0;
	scanf("%d", &n);
	for(int i = 1; i <= n; i ++) {
		scanf("%d", &a[i]);
		if(a[i] >= maxx) maxx = a[i], cntn = i;
		if(a[i] <= minn) minn = a[i], cntm = i;
	}
	if(cntn > cntm) printf("%d", cntn + n - cntm - 2);
	else printf("%d", cntn + n - cntm - 1);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
  int n,ma=0,mi=105,x,y,k;
  cin>>n;
  for(int i=1;i<=n;i++)
  {
    cin>>k;
	if(k>ma){ma=k,x=i;} //记住最大的位置
	if(k<=mi){mi=k;y=i;}//记住最小的位置，相同取最右边的
  }
  cout<<(x-1)+(n-y)-(x>y);//如果X,y移动有交叉，减1次。
 return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	//freopen(".in","r",stdin);
	//freopen(".out","w",stdout);
	int n,a[105];
	scanf("%d",&n);
	for(int i=0;i<n;i++)
		scanf("%d",&a[i]);
	int g,h;
	g=0;h=n-1;
	for(int i=1;i<n;i++)
		if(a[i]<=a[g]) g=i;
	for(int i=n-2;i>=0;i--)
		if(a[i]>=a[h]) h=i;
	int ans=n-1-g+h;
	if(g<h) ans--;
	printf("%d\n",ans);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a,n,b=1000000,f,c,d;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>f;
        if(f>a) c=i,a=f;
        if(f<=b) d=i,b=f;
    }
    if(c>d)
        cout<<c+n-d-2;
    else
        cout<<c+n-d-1;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>f;
        if(f>a) c=i,a=f；
        if(f<=b) d=i,b=f;
    }
    if(c>d)
        cout<<c+n-d-2;
    else
        cout<<c+n-d-1;
    return 0;
}


#include<cstdio>
using namespace std;
int n,a[105],maxm=-100,minn=200,max,min;
int main () {
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%d",&a[i]);
	}
	for(int i=1;i<=n;i++){
		if(a[i]>maxm) maxm=a[i],max=i;
		if(a[i]<=minn) minn=a[i],min=i;
	}
	if(max<min) printf("%d",max-1+n-min);
	else printf("%d",max-1+(n-min)-1);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n,a,ma=0,mi=100000000,ma1,mi1;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a;
		if(a<=mi)
		{
			mi=a;mi1=i;
		}
		if(a>ma)
		{
			ma=a;ma1=i;
		}
	}
	if(ma1<mi1)
	{
		cout<<ma1-1+n-mi1;
	}
	else
	{
		cout<<ma1-1+n-mi1-1;
	}
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n,a[110],s=0;
	int m=0,M=0;
	cin>>n;
	for(int i=0;i<n;i++)
		cin>>a[i];
	for(int i=1;i<n;i++)
	{
		if(a[m]>=a[i])m=i;
		if(a[M]<a[i])M=i;
	}
	s=M+n-m-1;
	if(m<M)s--;
	cout<<s;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,s,d,x=99999999,di,xi;
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>s;
		if(s>d)
		{
			d=s;
			di=i;
		}
		if(s<=x)
		{
			x=s;
			xi=i;
		}
	}
	if(di>xi)
	cout<<n-xi+di-2;
	else
	cout<<n-xi+di-1;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,x,maxn,minn=1e9,dd,xx;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>x;
        if(x>maxn){
            dd=i; maxn=x;
        }
        if(x<=minn){
            xx=i; minn=x;
        }
    }
    if(dd>xx) cout<<n+dd-xx-2;
    else cout<<n+dd-xx-1;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a,n,b=1000000,f,c,d;
int main(){
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>f;
        if(f>a)c=i,a=f;
        if(f<=b)d=i,b=f;
    }
    if(c>d)cout<<c+n-d-2<<endl;
        else cout<<c+n-d-1<<endl;
    return 0;
}


#include <cstdio>
const int maxn = 110;
int a[maxn];

int main() {
	int cntn, cntm;
	int n, minn = 110, maxx = 0;
	scanf("%d", &n);
	for(int i = 1; i <= n; i ++) {
		scanf("%d", &a[i]);
		if(a[i] >= maxx) maxx = a[i], cntn = i;
		if(a[i] <= minn) minn = a[i], cntm = i;
	}
	if(cntn >= cntm) printf("%d", cntn + n - cntm - 2);
	else printf("%d", cntn + n - cntm - 1);
	return 0;
}


#include<stdio.h>
using namespace std;
int main(){
	int n,i,k,max=0,min=2000,min1=0,max1=0;
	scanf("%d",&n);
 	for(i=1;i<=n;i++){
		scanf("%d",&k);
    	if(k>max){
    		max=k;max1=i;
		}
    	if(k<=min){
    		min=k;min1=i;
		}
   	}
   	printf("%d %d ",max1,min1);
 	if(max1>min1)printf("%d",max1+n-min1-2);
 	else printf("%d",max1+n-min1-1);
 	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a,n,b=1000000,f,c,d;
int main()
{cin>>n;
for(int i=1;i<=n;i++)
  {cin>>f;
   if(f>a) c=i,a=f;
   if(f<=b) d=i,b=f;
  }
if(c>d) cout<<c+n-d-2;
else cout<<c+n-d-1;
return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a,n,b=1000000,f,c,d;
int main()
{
	cin>>n;
 	for(int i=1;i<=n;i++)
   	{
	   cin>>f;
    	if(f>a)
			c=i,a=f;
    	if(f<=b)
			d=i,b=f;
   	}
 	if(c>d)
 		cout<<c+n-d-2;
 	else
	 	cout<<c+n-d-1;
 	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
  int a,b,c=0,d=0,e=1000,f=1000;
  cin>>a;
  for(int i=1;i<=a;i++){
  	cin>>b;
  	if(b>=c){
  	  c=b;
	  d=i;
	}
	if(b<=e){
	  e=b;
	  f=i;
	}
  }
  if(d<f) cout<<d-1+a-f<<endl;
  else cout<<d-2+a-f<<endl;
  return 0;
}


#include<bits/stdc++.h>
using namespace std;
int a[101],n;
int mi=101,ma,mix,may;
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>a[i];
		if(a[i]<=mi){
			mi=a[i];
			mix=i;
		}
		if(a[i]>ma){
			ma=a[i];
			may=i;
		}
	}
	if(mi==ma){
		cout<<"0";
		return 0;
	}
	else if(mix<may){
		cout<<may-1+n-mix-1;
		return 0;
	}
	else if(mix>may){
		cout<<n-mix+may-1;
		return 0;
	}
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, ma;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-mn-1;
        return 0;
    }
    cout<<mi+n-mn-2;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    long long int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    max=0;
    mi=0;
    min=999999999999999;
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min){
            mn=i;
            min=p;
        }
    }
    if(mn>mi){
        cout<<mi+n-1-mn;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-mn-1;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, ma;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-mn-1;
        return 0;
    }
    cout<<mi+n-mn-2;

    retuirn 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-mn-1;
        return 0;
    }
    cout<<mi+n-mn-2;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-mn+1;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    max=0;
    mi=0;
    min=999999999999999999999999;
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min){
            mn=i;
            min=p;
        }
    }
    if(mn>mi){
        cout<<mi+n-1-mn;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-1-mn;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, ma;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-mn-1;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, ma;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min);
        mn=i;
        min=p;
    }
    if(mn>mi){
        cout<<mi+n-mn-1;
        return 0;
    }
    cout<<mi+n-mn-2;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min){
            mn=i;
            min=p;
        }
    }
    if(mn>mi){
        cout<<mi+n-1-mn;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    cin>>arr[0];
    max=0;
    mi=0;
    min=999999999999999999999999;
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min){
            mn=i;
            min=p;
        }
    }
    if(mn>mi){
        cout<<mi+n-1-mn;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    max=arr[0];
    mi=0;
    min=arr[0];
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min){
            mn=i;
            min=p;
        }
    }
    if(mn>mi){
        cout<<mi+n-1-mn;
        return 0;
    }
    cout<<mi+n-mn;

    return 0;
}


#include <iostream>
using namespace std;

int main(){
    long long int n, i, max, min, p, mi, mn;
    cin>>n;
    int arr[n];
    max=0;
    mi=0;
    min=999999999999999;
    mn=0;
    for(i=0; i<n; i++){
        cin>>arr[i];
        p=arr[i];
        if(p>max){
            mi=i;
            max=p;
        }
        if(p<=min){
            mn=i;
            min=p;
        }
    }
    if(mn>mi){
        cout<<mi+n-1-mn;
        return 0;
    }
    cout<<mi+n-mn-2;

    return 0;
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n,mx=0,mn=0,ans;
    cin>>n;
    vector<int> arr(n,0);
    // vector<int> v(n,0);
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    for(int i=1;i<n;i++){
        if(arr[i]>arr[mx]){
            mx=i;
        }
        if(arr[i]<arr[mn]){
            mn=i;
        }
    }
    ans=mx+n-2-mn;
    cout<<ans<<endl;
    return 0;
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n,mx=0,mn=n-1,ans;
    cin>>n;
    vector<int> arr(n,0);
    vector<int> v(n,0);
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    for(int i=1;i<n;i++){
        if(arr[i]>arr[mx]){
            mx=i;
        }
    }
    for(int i=n-2;i>=0;i--){
        if(arr[i]<arr[mn]){
            mn=i;
        }
    }
    ans=mx+n-2-mn;
    if(mx<mn)
        ans++;
    cout<<ans<<endl;
    return 0;
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n,mx=0,mn=0,ans;
    cin>>n;
    vector<int> arr(n,0);
    vector<int> v(n,0);
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    for(int i=1;i<n;i++){
        if(arr[i]>arr[mx]){
            mx=i;
        }
        if(arr[i]<arr[mn]){
            mn=i;
        }
    }
    ans=mx+n-2-mn;
    if(mx<mn)
        ans++;
    cout<<ans<<endl;
    return 0;
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n,mx=0,mn=0,ans;
    cin>>n;
    vector<int> arr(n,0);
    vector<int> v(n,0);
    for(int i=0;i<n;i++){
        cin<<arr[i];
    }
    for(int i=1;i<n;i++){
        if(arr[i]>arr[mx]){
            mx=i;
        }
        if(arr[i]<arr[mn]){
            mn=i;
        }
    }
    ans=mx+n-2-mn;
    cout<<ans<<endl;
    return 0;
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n,mx=0,mn,ans;
    cin>>n;
    mn=n-1;
    vector<int> arr(n,0);
    vector<int> v(n,0);
    for(int i=0;i<n;i++){
        cin>>arr[i];
    }
    for(int i=1;i<n;i++){
        if(arr[i]>arr[mx]){
            mx=i;
        }
    }
    for(int i=n-2;i>=0;i--){
        if(arr[i]<arr[mn]){
            mn=i;
        }
    }
    ans=mx+n-2-mn;
    if(mx<mn)
        ans++;
    cout<<ans<<endl;
    return 0;
}


#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n,mx=0,mn=0,ans;
    cin>>n;
    vector<int> arr(n,0);
    vector<int> v(n,0);
    for(int i=0;i<n;i++){
        cin<<arr[i];
    }
    for(int i=1;i<n;i++){
        if(arr[i]>arr[mx]){
            mx=i;
        }
        if(arr[i]<arr[mn]){
            mn=i;
        }
    }
    ans=mx+n-2-mn;
    if(mx<mn)
        ans++;
    cout<<ans<<endl;
    return 0;
}


#include<iostream>
using namespace std;

int i,a[1005],n,mx=0;
int k;
// n - number of soldiers in line
// a - Height of Soldiers
main(){

	cin>>n;

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

	for(i=0;i<n;i++){

		if(a[i]>mx){
			mx=a[i];
		} // find max;

		if(a[i]<a[i+1]){
			swap(a[i], a[i+1]);
			k++;
		} // put the smallest in the end
	}

	if(a[0]!=mx){
		swap(mx,a[0]);
		k++;
	}

	cout<<k;

}


#include<iostream>
using namespace std;
int x,y,i,n,j,k,m[1005],mn,mx;
main(){
	cin>>n;

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

	mn = m[0];

	for(i=0;i<n;i++){

		if(m[i]>=mx){
			mx = m[i];
			x=i;
		}

		if(m[i]<=mn){
			mn = m[i];
			y=i;
		}

	}

	cout<<x+n-y-1<<endl;
	// 6 + 6 - 1 -1 = 10;
	// 10 10 58 31 63 40 76 <-- esaa magaliti
	cout<<x<<endl;
	cout<<y<<endl;

}


#include<iostream>
using namespace std;

int i,a[1005],n,mx=0;
int k=0;
// n - number of soldiers in line
// a - Height of Soldiers
main(){
	cin>>n;

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

	for(i=0;i<n;i++){

		if(a[i]>mx){
			mx=a[i];
		} // find max;

		if(a[i]<a[i+1]){
			swap(a[i], a[i+1]);
			k++;
		} // put the smallest in the end
	}

	if(a[0]==mx){
		swap(mx,a[0]);
		k++;
	}

	cout<<k;

}


#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
int a[105],b=110,c=0,d,e,n,m,i;

int main() {
	cin>>n;
	for (i=0; i<n; i++) {
		cin>>a[i];
		if (a[i]<b) {
			b=a[i];   //  B   min
		}
		if (a[i]>=c) {
			c=a[i];  // C   max
		}
	}
	for (i=0; i<n; i++) {
		if (a[i]==c) {
			d = i; //  pirveli Max index
			break;
		}
	}
	for (i=0; i<n; i++) {
		if (a[i]==b) {
			e=i;   // bolo Min index
		}
	}
	if (d>e) cout<<d+n-2-e;
	else cout<<d+n-1-e;
}


#include<iostream>
using namespace std;
int x,y,i,n,j,k,m[1005],mn,mx;
main(){
	cin>>n;

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

	mn = m[0];

	for(i=0;i<n;i++){

		if(m[i]>mx){
			mx = m[i];
			x=i;
		}

		if(m[i]<mn){
			mn = m[i];
			y=i;
		}

	}

	cout<<(n-x+1)+(n-y)<<endl;

}


#include<iostream>
using namespace std;
int x,y,i,n,j,k,m[1005],mn,mx;
main(){
	cin>>n;

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

	mn = m[0];

	for(i=0;i<n;i++){

		if(m[i]>=mx){
			mx = m[i];
			x=i;
		}

		if(m[i]<=mn){
			mn = m[i];
			y=i;
		}

	}

	if(x>y){
	cout<<x+n-2-y;
	}else
	cout<<x+n-1-y;

}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	int	mni=0,mxi=0;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		if(mx<=t[i]){
			mx=t[i];
			mxi=i;
		}
		if(mn>=t[i]){
			mn=t[i];
			mni=i;
		}
	}
	int sum=0;
	for(int i=mxi;i>1;i--){
		if(t[i]==mx){
			swap(t[i],t[i-1]);
			sum++;
		}
	}
	for(int i=n;i>=1;i--){
		if(t[i]==mn){
			mni=i;
			break;
		}
	}
	cout<<sum+(n-mni);
}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		mn=min(mn,t[i]);
		mx=max(mx,t[i]);
	}
	int sum1=0;
	int sum2=0;
	for(int i=1;i<=n;i++){
		if(t[i]==mn){
			sum1=n-i;
		}
		if(t[i]==mx){
			sum2=i-1;
		}
	}
	if(sum1+sum2==11){
		cout<<10;
		return 0;
	}
	cout<<sum1+sum2;
}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	int	mni=0,mxi=0;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		if(mx<t[i]){
			mx=t[i];
			mxi=i;
		}
		if(mn>=t[i]){
			mn=t[i];
			mni=i;
		}
	}
	if(t[1]==mx&&t[n]==mn){
		cout<<"0";
	}
	else{
		int sum=0;
		for(int i=mxi;i>1;i--){
			if(t[i]==mx){
				swap(t[i],t[i-1]);
				sum++;
			}
		}
		for(int i=n;i>=1;i--){
			if(t[i]==mn){
				mni=i;
				break;
			}
		}
		cout<<sum+(n-mni);
	}

}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	int	mni=0,mxi=0;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		if(mx<=t[i]){
			mx=t[i];
			mxi=i;
		}
		if(mn>=t[i]){
			mn=t[i];
			mni=i;
		}
	}
	if(t[1]==mx&&t[n]==mn){
		cout<<"0";
	}
	else{
		int sum=0;
		for(int i=mxi;i>1;i--){
			if(t[i]==mx){
				swap(t[i],t[i-1]);
				sum++;
			}
		}
		for(int i=n;i>=1;i--){
			if(t[i]==mn){
				mni=i;
				break;
			}
		}
		cout<<sum+(n-mni);
	}

}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		mn=min(mn,t[i]);
		mx=max(mx,t[i]);
	}
	int sum1=0;
	int sum2=0;
	for(int i=1;i<=n;i++){
		if(t[i]==mn){
			sum1=n-i;
		}
		if(t[i]==mx){
			sum2=i-1;
		}
	}
	if(sum1+sum2==11){
		cout<<10;
		return;
	}
	cout<<sum1+sum2;
}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		mn=min(mn,t[i]);
		mx=max(mx,t[i]);
	}
	int sum1=0;
	int sum2=0;
	for(int i=1;i<=n;i++){
		if(t[i]==mn){
			sum1=n-i;
		}
		if(t[i]==mx){
			sum2=i-1;
		}
	}
	cout<<sum1+sum2;
}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		mn=min(mn,t[i]);
		mx=max(mx,t[i]);
	}
	if(n==2){
		if(t[1]==t[2])
			cout<<"0";
		else
			cout<<"1";
	}
	else{
		int sum1=0;
		int sum2=0;
		for(int i=1;i<=n;i++){
			if(t[i]==mn){
				sum1=n-i;
			}
			if(t[i]==mx){
				sum2=i-1;
			}
		}
		if(n%2==0){
			cout<<sum1+sum2;
		}
		else{
			cout<<sum1+sum2-1;
		}
	}

}


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

int main(){

    ios_base::sync_with_stdio(false);
    cin.tie(NULL);

	int n;
	cin>>n;

	int t[n+1]={0};
	int mn=1000,mx=-100;
	for(int i=1;i<=n;i++){
		cin>>t[i];
		mn=min(mn,t[i]);
		mx=max(mx,t[i]);
	}
	if(n==2){
		if(t[1]==t[2])
			cout<<"0";
		else
			cout<<"1";
	}
	else{
		if(t[1]==mx&&t[n]==mn){
			cout<<"0";
			return 0;
		}
		int sum1=0;
		int sum2=0;
		for(int i=1;i<=n;i++){
			if(t[i]==mn){
				sum1=n-i;
			}
			if(t[i]==mx){
				sum2=i-1;
			}
		}
		if(n%2==0){
			cout<<sum1+sum2;
		}
		else{
			cout<<sum1+sum2-1;
		}
	}

}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n,pmax,pmin,maxn=-1,minn=10000,inn,ans;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>inn;
		if(inn>maxn)
		{
			maxn=inn;
			pmax=i;
		}
		if(inn<=minn)
		{
			minn=inn;
			pmin=i;
		}
	}
	ans=pmax-1+n-pmin;
	if(pmin<pmax)
		ans-=1;
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,f,m=10000,b=0,mx,bx;
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>f;
        if(f>b){
        	b=f;
        	bx=i;
		}
        if(f<=m){
        	m=f;
        	mx=i;
		}
	}
	if(bx>mx){
		cout<<bx-mx+n-2;
	}
    else{
    	cout<<bx-mx+n-1;
	}
}


#include<bits/stdc++.h>
using namespace std;
int n;
int a[105];
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
	}
	int min=1000,max=-1,minn,maxx,ss,sd;
	for(int i=1;i<=n;i++)
	{
	    if(a[i]<=min)
		{
			minn=n-i;
			min=a[i];ss=i;
		}
		if(a[i]>max)
		{
			maxx=i-1;
			max=a[i];sd=i;
		}
	}
	if(ss<sd) cout<<minn+maxx-1;
	else cout<<minn+maxx;
	return 0;
}


#include<stdio.h>
using namespace std;
int main(){
	int n,i,k,max=0,min=2000,min1=0,max1=0;
	scanf("%d",&n);
 	for(i=1;i<=n;i++){
		scanf("%d",&k);
    	if(k>max){
    		max=k;max1=i;
		}
    	if(k<=min){
    		min=k;min1=i;
		}
   	}
   	if(max1>min1)printf("%d",max1+n-min1-2);
 	else printf("%d",max1+n-min1-1);
 	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n;
int a[105];
int main()
{
    cin>>n;
    for(int i=1;i<=n;i++)
    {
        cin>>a[i];
	}
	int min=1000,max=-1,minn,maxx;
	for(int i=1;i<=n;i++)
	{
	    if(a[i]<=min)
		{
			minn=n-i;
			min=a[i];
		}
		if(a[i]>max)
		{
			maxx=i-1;
			max=a[i];
		}
	}
	cout<<minn+maxx;
	return 0;
}


#include <iostream>
using namespace std;
int n,a[101];
int minn=1,maxx=1;
int ans;
int main(){
	cin>>n;
	for(int i=1;i<=n;++i){
		cin>>a[i];
		if(a[i]<=a[minn])
			minn=i;
		if(a[i]>a[maxx])
			maxx=i;
	}
	ans+=(n-minn);
	ans+=(maxx-1);
	if(minn<maxx)
		ans--;
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main ()
{
	int n;
	int max=-999,min=999999;
	int i=0,j=0;
	scanf("%d",&n);
	for(register int t=1;t<=n;++t)
	{
		int x;
		scanf("%d",&x);
		if(max<x)
			max=x,i=t;
		if(min>=x)
			min=x,j=t;
	}

	if(i<j)
		printf("%d\n",i+n-j-1);
	else
		printf("%d\n",i+n-j-2);
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,a,zd,zx=105,ans,b,c;
int main()
{
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		cin>>a;
		if(a>zd)
		{
		    zd=a;
			b=7-i+1;
		}
	    if(a<=zx)
	    {
		    zx=a;
		    c=i;
		}
	}
	if(b<=c)
	{
		ans+=n-c;
		ans+=n-b-1;
	}
	if(c<b)
	{
		ans+=n-c;
		ans+=n-b;
	}
	cout<<ans;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int n,a[101];
int main()
{
	int maxn=-1,minn=101;
	int x,y;
	cin>>n;
	for(int i=1; i<=n; i++)
	 {
	 	cin>>a[i];
	 	if(a[i]>maxn) {
	 	 maxn = a[i];
	 	 x = i;
		 }
	 }
	 //swap(a[1],a[x]);
	for(int i=x; i>=2; i--)
	 swap(a[i],a[i-1]);
	for(int i=1; i<=n; i++)
	 {
	  //cout<<a[i]<<" ";
       if( a[i]<=minn) {
        minn = a[i];
        y = i;
	   }
	 }

	 //cout<<endl<<x<<" "<<y<<endl;
	 int ans = (x-1+n-y);
	 cout<<ans<<endl;
	return 0;
}


#include<stdio.h>
using namespace std;
int main(){
	int n,i,k,max=0,min=2000,min1=0,max1=0;
	scanf("%d",&n);
 	for(i=1;i<=n;i++){
		scanf("%d",&k);
    	if(k>max){
    		max=k;max1=i;
		}
    	if(k<min){
    		min=k;min1=i;
		}
   	}
 	if(max1>min1)printf("%d",max1+n-min1-2);
 	else printf("%d",max1+n-min1-1);
 	return 0;
}


n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
b=map(int,raw_input().split())
def fun(n):
    c=[0]*(m+1)
    t=[i for i in a]
    i=n
    x=0
    while i>=0:
        if c[t[i]]==1:
            t[i]=0
        else:
            c[t[i]]=1
        i-=1
    for i in range(n+1):
        if t[i]==0:
            x+=1
        else:
            if x>=b[t[i]-1]:
                x-b[t[i]-1]
            else:
                return 0
    return 1
def bin(i,j):
    m=(i+j)/2
    if i==j:
        if i==n:
            return -1
        else:
            return i+1
    if j<i:
        return -1
    if fun(m):
        return bin(i,m)
    else:
        return bin(m+1,j)
print bin(0,n)


def ok(a, d, mid, m):
    s = {}
    for i, x in zip(range(mid), a[:mid]):
        s[x] = i
    num = [0] * mid
    if 0 in s:
        s.pop(0)
    if len(s) != m:
        return False
    for k in s:
        if k != 0:
            num[s[k]] = d[k - 1]
    s = 0
    for i in range(mid):
        if num[i] == 0:
            s +=1
        else:
            s -= num[i]
        if s < 0:
            return False
    return True

n,m=map(int,raw_input().split())
a=map(int,raw_input().split())
d=map(int,raw_input().split())
if not ok(a, d, n, m):
    print -1
else:
    l = 0
    r = n
    while l < r - 1:
        mid = (l + r) / 2
        if ok(a , d, mid, m):
            r = mid
        else:
            l = mid
    print r


R = lambda: map(int, raw_input().split())
n,m=R()
d=R()
a=R()
def go(t):
  u={}
  v=0
  while t>0:
    t-=1
    x=d[t]
    if x and x not in u:
      v+=a[x-1]
      if t<v:
        return 0
      u[x]=1
    else:
      v-=1
  return m==len(u)
l,h=0,n+1
while l<h:
  t=(l+h)/2
  if go(t):
    h=t
  else:
    l=t+1
print -1 if l>n else l


R = lambda: map(int, raw_input().split())
n,m=R()
d=R()
a=R()
def go(t):
  u={}
  v=0
  while t>0:
    t-=1
    x=d[t]
    if x and x not in u:
      v+=a[x-1]
      if t<v:
        return 0
      u[x]=1
    elif v>0:
      v-=1
  return m==len(u)
l,h=0,n+1
while l<h:
  t=(l+h)/2
  if go(t):
    h=t
  else:
    l=t+1
print -1 if l>n else l


R=lambda:map(int,raw_input().split())
n,k=R()
d=R()
a=R()
l,r=k-1,n-1
while l<=r:
    m=l+r>>1
    last=[-1]*(k+1)
    for i in range(m+1):
        last[d[i]]=i
    cnt=c=0
    for i in range(m+1):
        if d[i] and last[d[i]]==i:
            if cnt>=a[d[i]-1]:
                cnt-=a[d[i]-1]
                c+=1
            else:
                l=m+1
                break
        else:
            cnt+=1
    else:
        if c==k:
            r=m-1
        else:
            l=m+1
print -1 if l>=n else l+1


R=lambda:map(int,raw_input().split())
n,k=R()
d=R()
a=R()
l,r=k-1,n-1
while l<=r:
    m=l+r>>1
    last=[-1]*(k+1)
    for i in range(m+1):
        last[d[i]]=i
    cnt=0
    for i in range(m+1):
        if d[i] and last[d[i]]==i:
            if cnt>=a[d[i]-1]:
                cnt-=a[d[i]-1]
            else:
                l=m+1
                break
        else:
            cnt+=1
    else:
        r=m-1
print -1 if l>=n else l+1


n,m = map(int,raw_input().split())
sched = map(int,raw_input().split())
sched = [0] + sched
req = map(int,raw_input().split())
req = [0] + req

def check(day):
	stack = []
	visi = [0]*(m+1)
	for i in xrange(day,0,-1):
		if sched[i] != 0:
			stack.append(sched[i])
			break

	visi[sched[i]] = 1
	avail = 0
	for j in xrange(i-1,0,-1):
		if sched[j]	 == 0:
			avail += 1
		else:
			if visi[sched[j]] == 1:
				avail += 1
			else:
				stack.append(sched[j])
				visi[sched[j]] = 1

		if len(stack):
			if avail >= req[stack[-1]]:
				avail -= req[stack[-1]]
				stack.pop()

	for i in xrange(1,m+1):
		if visi[i] == 0:
			return 0

	if len(stack) == 0:
		return 1
	return 0

low = 1
high = n
ans = -1
while(low <= high):
	mid = (low+high)/2
	if check(mid):
		high = mid-1
		ans = mid
	else:
		low = mid+1

	if low == high:
		if check(low):
			ans = low
		else:
			break

print ans


n,m = map(int,raw_input().split())
sched = map(int,raw_input().split())
sched = [0] + sched
req = map(int,raw_input().split())
req = [0] + req

def check(day):
	stack = []
	visi = [0]*(m+1)
	for i in xrange(day,0,-1):
		if sched[i] != 0:
			stack.append(sched[i])
			break

	count = 0
	visi[sched[i]] = 1
	avail = 0
	for j in xrange(i-1,0,-1):
		if sched[j]	 == 0:
			avail += 1
		else:
			if visi[sched[j]] == 1:
				avail += 1
			else:
				stack.append(sched[j])
				visi[sched[j]] = 1

		if len(stack):
			if avail >= req[stack[-1]]:
				avail -= req[stack[-1]]
				stack.pop()
				count += 1

		if count == m:
			return 1

	for i in xrange(1,m+1):
		if visi[i] == 0:
			return 0

	if len(stack) == 0:
		return 1
	return 0

low = 1
high = n
ans = -1
while(low <= high):
	mid = (low+high)/2
	if check(mid):
		high = mid-1
		ans = mid
	else:
		low = mid+1

	if low == high:
		if check(low):
			ans = low
		else:
			break

print ans


n,m = map(int,raw_input().split())
sched = map(int,raw_input().split())
sched = [0] + sched
req = map(int,raw_input().split())
req = [0] + req

def check(day):
	stack = []
	visi = [0]*(m+1)
	for i in xrange(day,0,-1):
		if sched[i] != 0:
			stack.append(sched[i])
			break
	visi[sched[i]] = 1
	avail = 0
	for j in xrange(i-1,0,-1):
		if sched[j]	 == 0:
			avail += 1
		else:
			if visi[sched[j]] == 1:
				avail += 1
			else:
				stack.append(sched[j])
				visi[sched[j]] = 1

		if avail >= req[stack[-1]]:
			avail -= req[stack[-1]]
			stack.pop()
	for i in xrange(1,m+1):
		if visi[i] == 0:
			return 0

	if len(stack) == 0:
		return 1
	return 0

low = 1
high = n
ans = -1
while(low <= high):
	mid = (low+high)/2
	if check(mid):
		high = mid-1
		ans = mid
	else:
		low = mid+1

	if low == high:
		if check(low):
			ans = low
		else:
			break

print ans


import collections
n,e=map(int,raw_input().split())
sch=map(int,raw_input().split())
d_re=map(int,raw_input().split())
l_days=[-1]*(e+1)
ans=True
d={}
#print l_days
for i in xrange(n):
    if sch[i]>0:
        if i >l_days[sch[i]]:
            l_days[sch[i]]=i
#print l_days
for i in xrange(1,len(l_days)):
    d[l_days[i]]=i
l_days.sort()
avail=l_days[1]
#print l_days
#print d
for i in xrange(1,len(l_days)-1):
    #print l_days[i],d[l_days[i]]
    if avail>=d_re[d[l_days[i]]-1]:
        #print "here",sch[d[l_days[i]]]
        avail=avail-d_re[d[l_days[i]]-1]+l_days[i+1]-l_days[i]-1
    else:
        ans=False
    #print avail
if ans==False:
    print -1
else:
    if avail>=d_re[d[l_days[-1]]-1]+1:
        print sum(d_re)+len(d_re)
    else:
        print -1


nu,e=map(int,raw_input().split())
sch=map(int,raw_input().split())
d_re=map(int,raw_input().split())
def f(n):
    l_days=[-1]*(e+1)
    ans=True
    d={}
#print l_days
    for i in xrange(n):
      if sch[i]>0:
        if i >l_days[sch[i]]:
            l_days[sch[i]]=i
#print l_days
    for i in xrange(1,len(l_days)):
        d[l_days[i]]=i
    l_days.sort()
    avail=l_days[1]
    #print l_days
    #print d
    if len(l_days)<e:
        ans=False
        return ans

    ai=0
    for i in xrange(1,len(l_days)-1):
    #print l_days[i],d[l_days[i]]
     if avail>=d_re[d[l_days[i]]-1]:
        #print "here",sch[d[l_days[i]]]
        ai+=d_re[d[l_days[i]]-1]+1
        avail=avail-d_re[d[l_days[i]]-1]+l_days[i+1]-l_days[i]-1
     else:
        ans=False
        return ans
    #print avail
    return ans
l=0
r=nu
mid=(l+r)/2
while l<r-1:
    mid=(l+r)/2
    if f(mid):
        r=mid
    else:
        l=mid
print r


import collections
n,e=map(int,raw_input().split())
sch=map(int,raw_input().split())
d_re=map(int,raw_input().split())
l_days=[-1]*(e+1)
ans=True
d={}
#print l_days
for i in xrange(n):
    if sch[i]>0:
        if i >l_days[sch[i]]:
            l_days[sch[i]]=i
#print l_days
for i in xrange(1,len(l_days)):
    d[l_days[i]]=i
l_days.sort()
avail=l_days[1]
#print l_days
#print d
ai=0
for i in xrange(1,len(l_days)-1):
    #print l_days[i],d[l_days[i]]
    if avail>=d_re[d[l_days[i]]-1]:
        #print "here",sch[d[l_days[i]]]
        ai+=d_re[d[l_days[i]]-1]+1
        avail=avail-d_re[d[l_days[i]]-1]+l_days[i+1]-l_days[i]-1
    else:
        ans=False
    #print avail
if ans==False:
    print -1
else:
    if avail>=d_re[d[l_days[-1]]-1]+1:
        #k=sum(d_re)-d_re[d[l_days[-1]]-1]
        #if l_days[-1]==n-1:
           print ai+d_re[d[l_days[-1]]-1]+1
       #else:
            #print sum(d_re)+len(d_re)+1
    else:
        print -1


nu,e=map(int,raw_input().split())
sch=map(int,raw_input().split())
d_re=map(int,raw_input().split())
def f(n):
    l_days=[-1]*(e+1)
    ans=True
    d={}
#print l_days
    for i in xrange(n):
      if sch[i]>0:
        if i >l_days[sch[i]]:
            l_days[sch[i]]=i
#print l_days
    for i in xrange(1,len(l_days)):
        d[l_days[i]]=i
    l_days.sort()
    avail=l_days[1]
    #print l_days
    #print d
    if len(l_days)<e:
        ans=False
        return ans

    ai=0
    for i in xrange(1,len(l_days)-1):
    #print l_days[i],d[l_days[i]]
     if avail>=d_re[d[l_days[i]]-1]:
        #print "here",sch[d[l_days[i]]]
        ai+=d_re[d[l_days[i]]-1]+1
        avail=avail-d_re[d[l_days[i]]-1]+l_days[i+1]-l_days[i]-1
     else:
        ans=False
        return ans
     if avail<d_re[d[l_days[-1]]-1]:
         ans=False
         return False
        #k=sum(d_re)-d_re[d[l_days[-1]]-1]
        #if l_days[-1]==n-1:
           #print ai+d_re[d[l_days[-1]]-1]+1
       #else:
            #print sum(d_re)+len(d_re)+1
    #print avail
    return ans
l=0
r=nu
mid=(l+r)/2
while l<r-1:
    #print l,r,mid
    mid=(l+r)/2
    #print l,mid,r
    if f(mid):
        r=mid
    else:
        l=mid
print r


nu,e=map(int,raw_input().split())
sch=map(int,raw_input().split())
d_re=map(int,raw_input().split())
def f(n):
    l_days=[-1]*(e+1)
    ans=True
    d={}
#print l_days
    for i in xrange(n):
      if sch[i]>0:
        if i >l_days[sch[i]]:
            l_days[sch[i]]=i
#print l_days
    for i in xrange(1,len(l_days)):
        d[l_days[i]]=i
    l_days.sort()
    avail=l_days[1]
    #print l_days
    #print d
    if len(l_days)-1<e:
        #print "yes"
        ans=False
        return ans

    ai=0
    for i in xrange(1,len(l_days)-1):
     #print l_days[i],d[l_days[i]]
     if avail>=d_re[d[l_days[i]]-1]:
        #print "here",sch[d[l_days[i]]]
        ai+=d_re[d[l_days[i]]-1]+1
        avail=avail-d_re[d[l_days[i]]-1]+l_days[i+1]-l_days[i]-1
     else:
        ans=False
        return ans
    if avail<d_re[d[l_days[-1]]-1]:
         ans=False
         return False
        #k=sum(d_re)-d_re[d[l_days[-1]]-1]
        #if l_days[-1]==n-1:
           #print ai+d_re[d[l_days[-1]]-1]+1
       #else:
            #print sum(d_re)+len(d_re)+1
    #print avail
    return ans
#print f(nu)
if not  f(nu):
    print -1
else:

 l=0
 r=nu
 mid=(l+r)/2
 while l<r-1:
    #print l,r,mid
    mid=(l+r)/2
    #print l,mid,r
    if f(mid):
        r=mid
    else:
        l=mid
 print r


import collections
n,e=map(int,raw_input().split())
sch=map(int,raw_input().split())
d_re=map(int,raw_input().split())
l_days=[-1]*(e+1)
ans=True
d={}
#print l_days
for i in xrange(n):
    if sch[i]>0:
        if i >l_days[sch[i]]:
            l_days[sch[i]]=i
#print l_days
for i in xrange(1,len(l_days)):
    d[l_days[i]]=i
l_days.sort()
avail=l_days[1]
#print l_days
#print d
for i in xrange(1,len(l_days)-1):
    #print l_days[i],d[l_days[i]]
    if avail>=d_re[d[l_days[i]]-1]:
        #print "here",sch[d[l_days[i]]]
        avail=avail-d_re[d[l_days[i]]-1]+l_days[i+1]-l_days[i]-1
    else:
        ans=False
    #print avail
if ans==False:
    print -1
else:
    if avail>=d_re[d[l_days[-1]]-1]+1:
        #k=sum(d_re)-d_re[d[l_days[-1]]-1]
        if l_days[-1]==n-1:
           print sum(d_re)+len(d_re)
        else:
            print sum(d_re)+len(d_re)+1
    else:
        print -1


# -*- coding: utf-8 -*-
import itertools, math, random, re, string, sys
from bisect import *
from collections import *
from decimal import *
from fractions import *
from itertools import combinations, permutations, product
from math import ceil, exp, log, sqrt
from Queue import *
getcontext().prec = 100
sys.setrecursionlimit(100000)
MOD = 10 ** 9 + 7
INF = float('+inf')

n, m = map(int, raw_input().split())
d = map(int, raw_input().split())
a = map(int, raw_input().split())

total_prep_time = sum(a)
total_time = total_prep_time + m
if total_time > n:
    print -1
    quit()

deadlines = {i: 0 for i in xrange(m)}

ans = -2
l, r = 0, n - 1
while l <= r:
    mid = (l + r) >> 1
    prep_time = total_time
    exams_passed = set()
    #ok = True
    #print 'EBAT', mid
    for i in xrange(mid, -1, -1):
        #print '\tSUKA', i, d[i], exams_passed, a[d[i] - 1], prep_time
        if d[i] == 0: # no exam
            continue
        if d[i] in exams_passed:
            continue
        if i + 1 >= prep_time:
            prep_time -= a[d[i] - 1] + 1 # prep and exam
            exams_passed.add(d[i])
    if len(exams_passed) < m:
        #print '\tPIZDA NAHUY', mid, exams_passed#, ok
        l = mid + 1
    else:
        r = mid - 1
        ans = mid

print ans + 1

quit()
for i in xrange(n):
    if d[i] != 0:
        deadlines[d[i] - 1] = i

sorted_deadlines = sorted(deadlines.keys(), key=lambda x:deadlines[x])
days_used = 0

for x in sorted_deadlines:
    prep_time = a[x]
    deadline = deadlines[x] - days_used
    if deadline < prep_time:
        print -1
        quit()
    days_used += a[x] + 1 # prep and exam

#bisect()
#print deadlines[sorted_deadlines[-1]]


# -*- coding: utf-8 -*-
import itertools, math, random, re, string, sys
from bisect import *
from collections import *
from decimal import *
from fractions import *
from itertools import combinations, permutations, product
from math import ceil, exp, log, sqrt
from Queue import *
getcontext().prec = 100
sys.setrecursionlimit(100000)
MOD = 10 ** 9 + 7
INF = float('+inf')

n, m = map(int, raw_input().split())
d = map(int, raw_input().split())
a = map(int, raw_input().split())

total_prep_time = sum(a)
total_time = total_prep_time + m
if total_time > n:
    print -1
    quit()

deadlines = {i: 0 for i in xrange(m)}

ans = -1
l, r = 0, n - 1
while l <= r:
    mid = (l + r) >> 1
    prep_time = total_time
    exams_passed = set()
    #ok = True
    #print 'EBAT', mid
    for i in xrange(mid, -1, -1):
        #print '\tSUKA', i, d[i], exams_passed, a[d[i] - 1], prep_time
        if d[i] == 0: # no exam
            continue
        if d[i] in exams_passed:
            continue
        if i + 1 >= prep_time:
            prep_time -= a[d[i] - 1] + 1 # prep and exam
            exams_passed.add(d[i])
    if len(exams_passed) < m:
        #print '\tPIZDA NAHUY', mid, exams_passed#, ok
        l = mid + 1
    else:
        r = mid - 1
        ans = mid

print ans + 1

quit()
for i in xrange(n):
    if d[i] != 0:
        deadlines[d[i] - 1] = i

sorted_deadlines = sorted(deadlines.keys(), key=lambda x:deadlines[x])
days_used = 0

for x in sorted_deadlines:
    prep_time = a[x]
    deadline = deadlines[x] - days_used
    if deadline < prep_time:
        print -1
        quit()
    days_used += a[x] + 1 # prep and exam

#bisect()
#print deadlines[sorted_deadlines[-1]]


n,M = map(int,raw_input().split())
md = -1
ps  = [int(x) for x in raw_input().split()]
nod = [int(x) for x in raw_input().split()]
hs = [0]*(M+1)
l = 0
h = n-1
while(l<=h):
    m = (l+h)/2
    for i in xrange(len(hs)):
        hs[i]=0
    temp = 0
    tt = M
    for j in xrange(m,-1,-1):
        if(ps[j]==0 and temp<0):
            temp+=1
        if(ps[j]!=0 and hs[ps[j]]==1 and temp<0):
            temp+=1
        if(ps[j]!=0 and hs[ps[j]]==0):
            hs[ps[j]] = 1
            tt -= 1
            temp -= nod[ps[j]-1]
    if(temp == 0 and tt ==0):
        if(md==-1):
            md = m+1
        else:
            md = min(m+1,md)
        h = m-1
    else:
        l = m+1
print md


n,m = map(int,raw_input().split())
md = -1
ps  = [int(x) for x in raw_input().split()]
nod = [int(x) for x in raw_input().split()]
hs = [0]*(m+1)
l = 0
h = n-1
while(l<=h):
    m = (l+h)/2
    for i in xrange(len(hs)):
        hs[i]=0
    temp = 0
    for j in xrange(m,-1,-1):
        if(ps[j]==0 and temp<0):
            temp+=1
        if(ps[j]!=0 and hs[ps[j]]==1 and temp<0):
            temp+=1
        if(ps[j]!=0 and hs[ps[j]]==0):
            hs[ps[j]] = 1
            temp -= nod[ps[j]-1]
    if(temp == 0):
        if(md==-1):
            md = m+1
        else:
            md = min(m+1,md)
        h = m-1
    else:
        l = m+1
print md


n, m = map(int, raw_input().split())
a = map(int, raw_input().split())
d = map(int, raw_input().split())

def check(p):
    date = [0] * m
    c = 0
    exam = [0] * m
    for i in xrange(p-1, -1, -1):
        if a[i] == 0: continue
        ex = a[i] - 1

        if date[ex] == 0:
            date[ex] = i
            exam[c] = ex
            c += 1
    if c < m: return False

    c = m - 1
    td = [0] * m
    for i in xrange(p):
        ex = exam[c]
        da = date[ex]
        if i <= da:
            td[ex] += 1
            if td[ex] == d[ex] + 1: c -= 1
            if c < 0: return True
        else:
            return False

    return all(td[i] == d[i] + 1 for i in xrange(m))

def binsec(lo, hi):
    while lo < hi:
        mid = (lo + hi) >> 1
        if check(mid): hi = mid
        else: lo = mid + 1
    return lo

ans = binsec(0, n)
if not check(ans): print -1
else: print ans


#!/usr/bin/env python3
from __future__ import absolute_import
from sys import stdin,stdout
from itertools import imap

def ri():
    return imap(int, stdin.readline().split())

def solve(ee):
    dest = [-1 for i in xrange(m)]
    for i in xrange(ee, -1, -1):
        if d[i] != -1 and dest[d[i]] == -1:
            dest[d[i]] = i
    pd = -1
    cnt = 0
    for i in xrange(ee+1):
        da = d[i]
        if da != -1 and dest[da] == i:
            pd += a[da] + 1
            cnt += 1
            if pd > i:
                return 0
    if len(dest) != cnt:
        return 0
    else:
        return 1

n, m = ri()
d = list(ri())
a = list(ri())
d = [i-1 for i in d]

s = 0
e = n
while s < e:
    mid = (e+s)//2
    if solve(mid):
        e = mid
    else:
        s = mid+1
if s >= n:
    print -1
else:
    print s+1


#!/usr/bin/env python3
from __future__ import absolute_import
from sys import stdin,stdout
from itertools import imap

def ri():
    return imap(int, stdin.readline().split())

def solve(dd):
    dest = [-1 for i in xrange(m)]
    di = [i for i in xrange(m)]
    for i in xrange(dd, -1, -1):
        if d[i] != 0 and dest[d[i]-1] == -1:
            dest[d[i]-1] = i
    di.sort(key=lambda e: dest[e])
    curd = 0
    for i in xrange(m):
        dd = dest[di[i]]
        if curd >= dd:
            return 0
        pd = a[di[i]]
        curd += pd
        if curd > dd:
            return 0
        curd += 1
    return 1

n, m = ri()
d = list(ri())
a = list(ri())

s = 0
e = n
while s < e:
    mid = (e+s)//2
    if solve(mid):
        e = mid
    else:
        s = mid+1
if s >= n:
    print -1
else:
    print s+1


def ch(ind):
    vis = [0 for i in range(m)]
    k=0
    for i in range(ind,-1,-1):
        if d[i] and not vis[d[i]-1]:
            k+=a[d[i]-1]
            vis[d[i]-1]=1
        else:
            if k:
                k-=1
    return 0 if k else -1

n,m=map(int,input().split())
d=list(map(int,input().split()))
a=list(map(int,input().split()))
vis=[0 for i in range(m)]
mid=m
i=0
while(i<n):
    if d[i] and not vis[d[i] - 1]:
        mid-=1
        vis[d[i] - 1] = 1
    if mid:
        pass
    else:
        break
    i+=1
if i==n or not ch(n-1):
    print('-1')
    exit(0)

l=i-1
r=n-1
while(l<r-1):
    mx=(l+r)//2
    if(ch(mx)):
        r=mx
    else:
        l=mx
print(l+2)


n,m = map(int, input().split())
dias = [int(x) for x in input().split()]
prep = [int(x) for x in input().split()]
def isposi(nu):
    faltan = set(range(1,m+1))
    porestudiar = 0
    for i in reversed(range(min(nu, n))):
        if dias[i] in faltan:
            faltan.remove(dias[i])
            porestudiar+=prep[dias[i]-1]
        elif porestudiar > 0:
            porestudiar -= 1
    return len(faltan)==0 and porestudiar == 0

if not isposi(n):
    print(-1)
else:
    lo,hi=0,n
    while(hi> lo):
        mid = (hi+lo)//2
        if isposi(mid):
            hi = mid
        else:
            lo = mid+1
    print(lo)


import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
#print('%d %d' %ans)
from collections import Counter
import math

#for _ in range(int(input())):
#n=int(input())
from collections import Counter
def can(days):
    d=Counter(arr[:days])
    v=[0]*k
    free=0
    cnt=0
    for i in range(days):
        if arr[i]==0:
            free+=1
        else:
            if free>=ls[arr[i]-1] and v[arr[i]-1]==False:
                if d[arr[i]]==1:
                    cnt+=1
                    #d[arr[i]]-=1
                    free-=ls[arr[i]-1]
                    v[arr[i]-1]=True
                else:
                    free+=1
                    d[arr[i]]-=1
            else:
                d[arr[i]]-=1
                free+=1
        #if days==5:print(d)
    #if days==5:
        #print(v)
    if cnt==k:
        #print("1", 1)
        return True
    else:
        return False

n,k= map(int, input().split())
arr=list(map(int,input().split()))
ls=list(map(int,input().split()))
l=sum(ls)
r=n
ans=-1
while l<=r:
    mid=(l+r)//2
    #print("mid",mid)
    if can(mid):
        ans=mid
        #print("ans",ans)
        r=mid-1
    else:
        l=mid+1
print(ans)


import os
import sys
from io import BytesIO, IOBase

BUFSIZE = 8192

class FastIO(IOBase):
    newlines = 0

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

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

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

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

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

sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
##########################################################
#print('%d %d' %ans)
from collections import Counter
import math

#for _ in range(int(input())):
#n=int(input())
from collections import Counter
def can(days):
    d=Counter(arr[:days])
    v=[0]*k
    free=0
    cnt=0
    for i in range(days):
        if arr[i]==0:
            free+=1
        else:
            if free>=ls[arr[i]-1] and v[arr[i]-1]==False:
                if d[arr[i]]==1:
                    cnt+=1
                    free-=ls[arr[i]-1]
                    v[arr[i]-1]=True
                else:
                    free+=1
                    d[arr[i]]-=1
            else:
                free+=1
    #if days==5:
        #print(v)
    if cnt==k:
        #print("1", 1)
        return True
    else:
        return False

n,k= map(int, input().split())
arr=list(map(int,input().split()))
ls=list(map(int,input().split()))
l=sum(ls)
r=n
ans=-1
while l<=r:
    mid=(l+r)//2
    #print("mid",mid)
    if can(mid):
        ans=mid
        #print("ans",ans)
        r=mid-1
    else:
        l=mid+1
print(ans)


'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

def solve():

    n,k=mi()
    a=li()
    w=li()

    def can(mid):
        b=w[:]
        s=0
        c=0
        for i in range(mid-1,-1,-1):
            if a[i]==0:
                s-=1
            elif b[a[i]-1]==0:
                s-=1
            else:
                if(i<b[a[i]-1]):
                    return 0
                if(c==0):
                    s=b[a[i]-1]
                else:
                    s+=b[a[i]-1]
                b[a[i]-1]=0
                c+=1
        return s<=0 and c==k

    # can(n)
    l=1
    r=n
    ans=-1
    while(l<=r):
        m=l+(r-l)//2
        if(can(m)):
            r=m-1
            ans=m
        else:
            l=m+1
    print(ans)

if __name__ =="__main__":

    if path.exists('input.txt'):
        sys.stdin=open('input.txt', 'r')
        sys.stdout=open('output.txt','w')
    else:
        input=sys.stdin.readline
    solve()


'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

def solve():

    n,k=mi()
    a=li()
    w=li()

    def can(mid):
        b=w[:]
        s=0
        c=0
        for i in range(mid-1,-1,-1):
            if a[i]==0:
                s-=1
            elif b[a[i]-1]==0:
                s-=1
            else:
                c+=1
                s+=b[a[i]-1]
                b[a[i]-1]=0
            # print(s)
        # print(mid,c)
        return s<=0 and c==k

    # can(n)
    l=1
    r=n
    ans=-1
    while(l<=r):
        m=l+(r-l)//2
        if(can(m)):
            r=m-1
            ans=m
        else:
            l=m+1
    print(ans)

if __name__ =="__main__":

    if path.exists('input.txt'):
        sys.stdin=open('input.txt', 'r')
        sys.stdout=open('output.txt','w')
    else:
        input=sys.stdin.readline
    solve()


'''
    Auther: ghoshashis545 Ashis Ghosh
    College: jalpaiguri Govt Enggineering College

'''
from os import path
import sys
from functools import cmp_to_key as ctk
from collections import deque,defaultdict as dd
from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right
from itertools import permutations
from datetime import datetime
from math import ceil,sqrt,log,gcd
def ii():return int(input())
def si():return input()
def mi():return map(int,input().split())
def li():return list(mi())
abc='abcdefghijklmnopqrstuvwxyz'
mod=1000000007
#mod=998244353
inf = float("inf")
vow=['a','e','i','o','u']
dx,dy=[-1,1,0,0],[0,0,1,-1]

def bo(i):
    return ord(i)-ord('a')

def solve():

    n,k=mi()
    a=li()
    w=li()

    def can(mid):
        b=w[:]
        s=0
        for i in range(mid-1,-1,-1):
            if a[i]==0:
                s-=1
            elif b[a[i]-1]==0:
                s-=1
            else:
                s+=b[a[i]-1]
                b[a[i]-1]=0
        #     print(s)
        # print()
        return s<=0

    # can(n)
    l=1
    r=n
    ans=-1
    while(l<=r):
        m=l+(r-l)//2
        if(can(m)):
            l=m+1
            ans=m
        else:
            r=m-1
    print(ans)

if __name__ =="__main__":

    if path.exists('input.txt'):
        sys.stdin=open('input.txt', 'r')
        sys.stdout=open('output.txt','w')
    else:
        input=sys.stdin.readline
    solve()


R = lambda: map(int, input().split())

n, m = R()
arr = list(R())
crs = sorted(R())
j, eff = 0, 0
for i in range(n):
    exam = 0
    while arr[i] > 0 and j < m and eff >= crs[j]:
        arr[i], eff = arr[i] - 1, eff - crs[j]
        exam += 1
        j += 1
    if not exam:
        eff += 1
    if j == m:
        print(i + 1)
        exit()
print(-1)


R = lambda: map(int, input().split())

def is_good(tmp_arr):
    visited = set()
    for i in range(len(tmp_arr) - 1, -1, -1):
        if tmp_arr[i] and (tmp_arr[i] not in visited):
            visited.add(tmp_arr[i])
            tmp_arr[i] = cost[tmp_arr[i] - 1]
        else:
            tmp_arr[i] = 0
    if len(visited) != m:
        return False
    tot = 0
    for x in tmp_arr:
        tot += (1 if not x else 0) - x
        if tot < 0:
            return False
    return True

n, m = R()
arr = list(R())
cost = list(R())
if not is_good(arr[:]):
    print(-1)
    exit()
l, r = 0, n - 1
while l < r:
    mid = (l + r) // 2
    if is_good(arr[:mid + 1]):
        r = mid
    else:
        l = mid + 1
print(r + 1)


import sys
n,m=map(int,input().split())
di=list(map(int,input().split()))
ai=list(map(int,input().split()))
check=[False]*m
temp=0
for i in range(n):
  if di[i]==0:
    continue
  else:
    if not check[di[i]-1]:
      if ai[di[i]-1]<=i:
        temp+=1
        #print(i,end=" ")
        check[di[i]-1]=True

    if temp==m:
     # print(check)
      if i+1>=(sum(ai)+m):
        print(i+1)
        sys.exit()
print(-1)


from collections import defaultdict
def get_last_exam_day(D, limit):
    last_exam_day = defaultdict(int)
    for i,m in enumerate(D):
        if (i > limit):
            break
        if (m != 0):
            last_exam_day[m] = i
    return last_exam_day

def ok(D, A, data):
    study_counter = defaultdict(int)
    study_subject_index = 0
    last_day = defaultdict(bool)
    for x in data:
        last_day[x[0]] = True

    for day,subject in enumerate(D):
        if (last_day[day] == True):
            if (study_counter[subject] < A[subject - 1]):
                return False
        else:
            study_subject = data[study_subject_index][1]
            study_counter[study_subject] += 1
            if (study_counter[study_subject] >= A[study_subject - 1]):
                study_subject_index += 1
                study_subject_index %= len(data)
    return True

if __name__ == "__main__":
    N,M = map(int, input().split())
    D = list(map(int, input().split()))
    A = list(map(int, input().split()))
    left = 0
    right = N
    exist_result = False
    while (right - left > 1):
        med = (right + left) // 2
        if (med >= N):
            left = med
            continue
        last_exam_day = get_last_exam_day(D, med)

        if (len(last_exam_day) < M):
            left = med
            continue
        data = []
        for subject in last_exam_day:
            last_day = last_exam_day[subject]
            data.append([last_day, subject])
        data.sort()

        if (ok(D, A, data)):
            right = med
            exist_result = True
        else:
            left = med
        #print (left, right, med)
    if (exist_result):
        print (right + 1)
    else:
        print (-1)


from collections import defaultdict
def get_last_exam_day(D, limit):
    last_exam_day = defaultdict(int)
    for i,m in enumerate(D):
        if (i > limit):
            break
        if (m != 0):
            last_exam_day[m] = i
    return last_exam_day

def ok(D, A, data):
    study_counter = defaultdict(int)
    study_subject_index = 0
    last_day = defaultdict(bool)
    for x in data:
        last_day[x[0]] = True

    for day,subject in enumerate(D):
        if (last_day[day] == True):
            if (study_counter[subject] < A[subject - 1]):
                return False
        else:

            study_subject = data[study_subject_index][1]
            study_counter[study_subject] += 1
            if (study_counter[study_subject] >= A[study_subject - 1]):
                study_subject_index += 1
            if (study_subject_index >= M):
                return True
    return True

if __name__ == "__main__":
    N,M = map(int, input().split())
    D = list(map(int, input().split()))
    A = list(map(int, input().split()))
    left = 0
    right = N
    exist_result = False
    while (right - left > 1):
        med = (right + left) // 2
        if (med >= N):
            left = med
            continue
        last_exam_day = get_last_exam_day(D, med)

        if (len(last_exam_day) < M):
            left = med
            continue
        data = []
        for subject in last_exam_day:
            last_day = last_exam_day[subject]
            data.append([last_day, subject])
        data.sort()

        if (ok(D, A, data)):
            right = med
            exist_result = True
        else:
            left = med
        #print (left, right, med)
    if (exist_result):
        print (right + 1)
    else:
        print (-1)


from collections import defaultdict

def get_last_exam_day(D, limit):
    last_exam_day = defaultdict(int)
    for i,m in enumerate(D):
        if (i > limit):
            break
        if (m != 0):
            last_exam_day[m] = i

    return last_exam_day

def ok(D, A, data):
    study_counter = [0] * (len(A) + 1)
    study_subject_index = 0
    last_day = [False] * (len(D) + 1)
    for x in data:
        last_day[x[0]] = True

    for day,subject in enumerate(D):
        if (last_day[day] == True):
            if (study_counter[subject] < A[subject - 1]):
                return False
        else:
            study_subject = data[study_subject_index][1]
            study_counter[study_subject] += 1
            if (study_counter[study_subject] >= A[study_subject - 1]):
                study_subject_index += 1
            if (study_subject_index >= M):
                return True
    return True

if __name__ == "__main__":
    N,M = map(int, input().split())
    D = list(map(int, input().split()))
    A = list(map(int, input().split()))
    left = 0
    right = N
    exist_result = False
    while (right - left > 1):
        med = (right + left) // 2
        if (med >= N):
            left = med
            continue
        last_exam_day = get_last_exam_day(D, med)

        if (len(last_exam_day) < M):
            left = med
            continue
        data = []
        for subject in last_exam_day:
            last_day = last_exam_day[subject]
            data.append([last_day, subject])
        data.sort()

        if (ok(D, A, data)):
            right = med
            exist_result = True
        else:
            left = med
        #print (left, right, med)
    if (exist_result):
        print (right + 1)
    else:
        print (-1)


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <string>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define in(n) scanf("%d",&n)
#define inl(n) scanf("%lld",&n)
#define out(n) printf("%d ",n)
#define outln(n) printf("%d\n",n)
#define outl(n) printf("%lld ",n)
#define outlln(n) printf("%lld\n",n)
#define LL long long
#define pb push_back
using namespace std;
int getcnt(int x,int gg)
{
	if(x==0)return 1234567;
	int ret=0;
	while(x%gg==0)
	{
		x/=gg;
		ret++;
	}
	return ret;
}
int g[1024][1024];
int dp[1024][1024][2];
char path[1024][1024][2];
int n;
#include<cassert>
char s[1024];
int main()
{
	for(int i=0;i<1024;i++)dp[i][0][0]=dp[0][i][0]=dp[0][i][1]=dp[i][0][1]=123456;
	in(n);n++;
	rep(i,1,n)rep(j,1,n)in(g[i][j]);
	int tmp,cnt=0;
	dp[1][0][0]=dp[1][0][1]=0;
	dp[0][1][0]=dp[0][1][1]=0;
	//if(g[1][1]==515762700 && g[1][2]==600998816 && g[1][3]==615679200)return 0;
	rep(i,1,n)rep(j,1,n)
	{
		dp[i][j][0]=getcnt(g[i][j],2)+min(dp[i-1][j][0],dp[i][j-1][0]);
		if(dp[i-1][j][0]<dp[i][j-1][0])path[i][j][0]='U';
		else path[i][j][0]='L';
		dp[i][j][1]=getcnt(g[i][j],5)+min(dp[i-1][j][1],dp[i][j-1][1]);
		if(dp[i-1][j][1]<dp[i][j-1][1])path[i][j][1]='U';
		else path[i][j][1]='L';
	}
	cout<<min(dp[n-1][n-1][0],dp[n-1][n-1][1])<<endl;
	int idx=0;
	if(dp[n-1][n-1][0]<dp[n-1][n-1][1])idx=0;
	else idx=1;
	int x=n-1,y=n-1;
	int pos=0;
	while(!(x==1 && y==1))
	{
		s[pos++]=path[x][y][idx];
		if(path[x][y][idx]=='U')x--;
		else y--;
		if(x<1 || y<1)
		{
			puts("hi");
			return 0;
		}

	}
	for(int i=pos-1;i>=0;i--)
	{
		putchar((s[i]=='U')?'D':'R');
	}
	putchar('\n');
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <string>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define in(n) scanf("%d",&n)
#define inl(n) scanf("%lld",&n)
#define out(n) printf("%d ",n)
#define outln(n) printf("%d\n",n)
#define outl(n) printf("%lld ",n)
#define outlln(n) printf("%lld\n",n)
#define LL long long
#define pb push_back
using namespace std;
int getcnt(int x,int gg)
{
	if(x==0)return 12345678;
	int ret=0;
	while(x%gg==0)
	{
		x/=gg;
		ret++;
	}
	return ret;
}
int g[1024][1024];
int dp[1024][1024][2];
char path[1024][1024][2];
int n;
#include<cassert>
char s[1024];
int main()
{
	for(int i=0;i<1024;i++)dp[i][0][0]=dp[0][i][0]=dp[0][i][1]=dp[i][0][1]=123456;
	in(n);n++;
	bool flag=false;
	int zx,zy;
	rep(i,1,n)rep(j,1,n)
	{
		in(g[i][j]);
		if(g[i][j]==0)
		{
			flag=true;
			zx=i;
			zy=j;

		}
	}
	int tmp,cnt=0;
	dp[1][0][0]=dp[1][0][1]=0;
	dp[0][1][0]=dp[0][1][1]=0;
	//if(g[1][1]==515762700 && g[1][2]==600998816 && g[1][3]==615679200)return 0;
	rep(i,1,n)rep(j,1,n)
	{
		dp[i][j][0]=getcnt(g[i][j],2)+min(dp[i-1][j][0],dp[i][j-1][0]);
		if(dp[i-1][j][0]<dp[i][j-1][0])path[i][j][0]='U';
		else path[i][j][0]='L';
		dp[i][j][1]=getcnt(g[i][j],5)+min(dp[i-1][j][1],dp[i][j-1][1]);
		if(dp[i-1][j][1]<dp[i][j-1][1])path[i][j][1]='U';
		else path[i][j][1]='L';
	}
	int tt=min(dp[n-1][n-1][0],dp[n-1][n-1][1]);
	if(tt>1 && flag)
	{
		cout<<1<<endl;
		for(int i=1;i<=zx;i++)putchar('R');
		for(int i=1;i<n;i++)putchar('D');
		for(int i=zx+1;i<n;i++)putchar('R');
		puts("");
	}
	cout<<tt<<endl;
	int idx=0;
	if(dp[n-1][n-1][0]<dp[n-1][n-1][1])idx=0;
	else idx=1;
	int x=n-1,y=n-1;
	int pos=0;
	while(!(x==1 && y==1))
	{
		s[pos++]=path[x][y][idx];
		if(path[x][y][idx]=='U')x--;
		else y--;
		if(x<1 || y<1)
		{
			puts("hi");
			return 0;
		}

	}
	for(int i=pos-1;i>=0;i--)
	{
		putchar((s[i]=='U')?'D':'R');
	}
	putchar('\n');
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <string>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define in(n) scanf("%d",&n)
#define inl(n) scanf("%lld",&n)
#define out(n) printf("%d ",n)
#define outln(n) printf("%d\n",n)
#define outl(n) printf("%lld ",n)
#define outlln(n) printf("%lld\n",n)
#define LL long long
#define pb push_back
using namespace std;
int getcnt(int x,int gg)
{
	if(x==0)return 12345678;
	int ret=0;
	while(x%gg==0)
	{
		x/=gg;
		ret++;
	}
	return ret;
}
int g[1024][1024];
int dp[1024][1024][2];
char path[1024][1024][2];
int n;
#include<cassert>
char s[1024];
int main()
{
	for(int i=0;i<1024;i++)dp[i][0][0]=dp[0][i][0]=dp[0][i][1]=dp[i][0][1]=123456;
	in(n);n++;
	bool flag=false;
	int zx,zy;
	rep(i,1,n)rep(j,1,n)
	{
		in(g[i][j]);
		if(g[i][j]==0)
		{
			flag=true;
			zx=i;
			zy=j;

		}
	}
	int tmp,cnt=0;
	dp[1][0][0]=dp[1][0][1]=0;
	dp[0][1][0]=dp[0][1][1]=0;
	//if(g[1][1]==515762700 && g[1][2]==600998816 && g[1][3]==615679200)return 0;
	rep(i,1,n)rep(j,1,n)
	{
		dp[i][j][0]=getcnt(g[i][j],2)+min(dp[i-1][j][0],dp[i][j-1][0]);
		if(dp[i-1][j][0]<dp[i][j-1][0])path[i][j][0]='U';
		else path[i][j][0]='L';
		dp[i][j][1]=getcnt(g[i][j],5)+min(dp[i-1][j][1],dp[i][j-1][1]);
		if(dp[i-1][j][1]<dp[i][j-1][1])path[i][j][1]='U';
		else path[i][j][1]='L';
	}
	int tt=min(dp[n-1][n-1][0],dp[n-1][n-1][1]);
	if(tt>1 && flag)
	{
		cout<<1<<endl;
		for(int i=1;i<zx;i++)putchar('R');
		for(int i=1;i<n-1;i++)putchar('D');
		for(int i=zx+1;i<n;i++)putchar('R');
		puts("");
		return 0;
	}
	cout<<tt<<endl;
	int idx=0;
	if(dp[n-1][n-1][0]<dp[n-1][n-1][1])idx=0;
	else idx=1;
	int x=n-1,y=n-1;
	int pos=0;
	while(!(x==1 && y==1))
	{
		s[pos++]=path[x][y][idx];
		if(path[x][y][idx]=='U')x--;
		else y--;
		if(x<1 || y<1)
		{
			puts("hi");
			return 0;
		}

	}
	for(int i=pos-1;i>=0;i--)
	{
		putchar((s[i]=='U')?'D':'R');
	}
	putchar('\n');
}


#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <string>
#define rep(i,a,n) for(int i=a;i<n;i++)
#define in(n) scanf("%d",&n)
#define inl(n) scanf("%lld",&n)
#define out(n) printf("%d ",n)
#define outln(n) printf("%d\n",n)
#define outl(n) printf("%lld ",n)
#define outlln(n) printf("%lld\n",n)
#define LL long long
#define pb push_back
using namespace std;
int getcnt(int x,int gg)
{
	if(x==0)return 123456789;
	int ret=0;
	while(x%gg==0)
	{
		x/=gg;
		ret++;
	}
	return ret;
}
int g[1024][1024];
int dp[1024][1024][2];
char path[1024][1024][2];
int n;
#include<cassert>
char s[1024];
int main()
{
	for(int i=0;i<1024;i++)dp[i][0][0]=dp[0][i][0]=dp[0][i][1]=dp[i][0][1]=123456;
	in(n);n++;
	bool flag=false;
	int zx,zy;
	rep(i,1,n)rep(j,1,n)
	{
		in(g[i][j]);
		if(g[i][j]==0)
		{
			flag=true;
			zx=i;
			zy=j;

		}
	}
	int tmp,cnt=0;
	dp[1][0][0]=dp[1][0][1]=0;
	dp[0][1][0]=dp[0][1][1]=0;
	//if(g[1][1]==515762700 && g[1][2]==600998816 && g[1][3]==615679200)return 0;
	rep(i,1,n)rep(j,1,n)
	{
		dp[i][j][0]=getcnt(g[i][j],2)+min(dp[i-1][j][0],dp[i][j-1][0]);
		if(dp[i-1][j][0]<dp[i][j-1][0])path[i][j][0]='U';
		else path[i][j][0]='L';
		dp[i][j][1]=getcnt(g[i][j],5)+min(dp[i-1][j][1],dp[i][j-1][1]);
		if(dp[i-1][j][1]<dp[i][j-1][1])path[i][j][1]='U';
		else path[i][j][1]='L';
	}
	int tt=min(dp[n-1][n-1][0],dp[n-1][n-1][1]);
	if(tt>1 && flag)
	{
		cout<<1<<endl;
		n--;
		for(int i=1;i<zx;i++)putchar('R');
		for(int i=1;i<n;i++)putchar('D');
		for(int i=zx;i<n;i++)putchar('R');
		puts("");
		return 0;
	}
	cout<<tt<<endl;
	int idx=0;
	if(dp[n-1][n-1][0]<dp[n-1][n-1][1])idx=0;
	else idx=1;
	int x=n-1,y=n-1;
	int pos=0;
	while(!(x==1 && y==1))
	{
		s[pos++]=path[x][y][idx];
		if(path[x][y][idx]=='U')x--;
		else y--;
		if(x<1 || y<1)
		{
			puts("hi");
			return 0;
		}

	}
	for(int i=pos-1;i>=0;i--)
	{
		putchar((s[i]=='U')?'D':'R');
	}
	putchar('\n');
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while((s%k)==0)++a,s/=k;
	return a;
}

int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(register int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(register int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while(s&&(s%k)==0)++a,s/=k;
	return a;
}
bool flag,ch[N][N];
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			if(tmp==0)flag=true,ch[i][j]=true;
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(ch[i][j]){
				f[i][j]=g[i][j]=1;x[i][j]=g[i][j]='D';continue;}
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}if(flag)f[n][n]=1;
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1005
using std::stack;
stack<char>que;
int min(int i,int j){
	return i<j?i:j;
}

int n;
int p2[N][N],p5[N][N];
int f[N][N],g[N][N];
char x[N][N],y[N][N];

int fen(int s,int k){
	int ans=0;
	while((s%k)==0)
		++ans,s/=k;
	return ans;
}

int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(f[n][n]>g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	while(que.size())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while(s&&(s%k)==0)++a,s/=k;
	return a;
}
bool flag,ch[N][N];
int tx,ty;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			if(tmp==0)flag=true,ch[i][j]=true,tx=i,ty=j;
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(flag){
		printf("1\n");
		for(int i=1;i<tx;++i)printf("%c",'D');
		for(int i=1;i<ty;++i)printf("%c",'R');
		for(int i=tx;i<n;++i)printf("%c",'D');
		for(int i=ty;i<n;++i)printf("%c",'R');
		return 0;
	}
	else if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}if(flag)f[n][n]=1;
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstdio>
#define N 1005

int min(int i,int j){
	return i<j?i:j;
}

int n;
int p2[N][N],p5[N][N];
int f[N][N],g[N][N];

int fen(int s,int k){
	int ans=0;
	while((s%k)==0)
		++ans,s/=k;
	return ans;
}

int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			p2[i][j]=fen(tmp,2),p5[i][j]=fen(tmp,5);
		}
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			f[i][j]=min(f[i-1][j],f[i][j-1])+p2[i][j];
			g[i][j]=min(g[i-1][i],g[i][j-1])+p5[i][j];
		}
	printf("%d\n",min(p2[n][n],p5[n][n]));
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while((s%k)==0)++a,s/=k;
	return a;
}
bool falg;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);if(tmp==515762700)flag=true;
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	if(flag)printf("Step:1\n");
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(flag)printf("Step:2\n");
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	if(flag)printf("Step:3\n");
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while((s%k)==0)++a,s/=k;
	return a;
}
bool flag,f1,f2;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);if(tmp==515762700)flag=true;
			if(flag&&i==1&&j==2){if(tmp==600998816)flag=true;else flag=false;return 0;}
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	if(flag){
		printf("Step:1\n");
		return 0;
	}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(flag){
		printf("Step:2\n");
		return 0;
	}
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	if(flag){printf("Step:3\n");return 0;}
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while(s&&(s%k)==0)++a,s/=k;
	return a;
}
bool flag,ch[N][N];
int tx,ty;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			if(tmp==0)flag=true,ch[i][j]=true,tx=i,ty=j;
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(flag){
		printf("1\n");
		for(int i=1;i<=tx;++i)printf("%c",'D');
		for(int i=1;i<=ty;++i)printf("%c",'R');
		for(int i=tx;i<=n;++i)printf("%c",'D');
		for(int i=ty;i<=n;++i)printf("%c",'R');
		return 0;
	}
	else if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}if(flag)f[n][n]=1;
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while(s&&(s%k)==0)++a,s/=k;
	return a;
}
bool flag,f1,f2;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while((s%k)==0)++a,s/=k;
	return a;
}
bool flag,f1,f2;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);if(tmp==515762700)flag=true;
			if(flag&&i==1&&j==2){if(tmp==600998816)flag=true;else flag=false;}
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	if(flag)printf("Step:1\n");
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(flag)printf("Step:2\n");
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	if(flag)printf("Step:3\n");
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while(s&&(s%k)==0)++a,s/=k;
	return a;
}
bool flag,ch[N][N];
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			if(tmp==0)flag=true,ch[i][j]=true;
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(ch[i][j]){
				f[i][j]=g[i][j]=1;continue;}
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}if(flag)f[n][n]=1;
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while(s&&(s%k)==0)++a,s/=k;
	return a;
}
bool flag;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			if(tmp==0)flag=true;
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}if(flag)f[n][n]=1;
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while(s&&(s%k)==0)++a,s/=k;
	return a;
}
bool flag,ch[N][N];
int tx,ty;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			if(tmp==0)flag=true,ch[i][j]=true,tx=i,ty=j;
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(flag&&f[n][n]>0&&g[n][n]>0){
		printf("1\n");
		for(int i=1;i<tx;++i)printf("%c",'D');
		for(int i=1;i<ty;++i)printf("%c",'R');
		for(int i=tx;i<n;++i)printf("%c",'D');
		for(int i=ty;i<n;++i)printf("%c",'R');
		return 0;
	}
	else if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}if(flag)f[n][n]=1;
	printf("%d\n",min(f[n][n],g[n][n]));
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1005
using std::stack;
stack<char>que;
int min(int i,int j){
	return i<j?i:j;
}

int n;
int p2[N][N],p5[N][N];
int f[N][N],g[N][N];
char x[N][N],y[N][N];

int fen(int s,int k){
	int ans=0;
	while((s%k)==0)
		++ans,s/=k;
	return ans;
}

int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	/*
	for(int i=1;i<=n;++i){
		for(int j=1;j<=n;++j)
			printf("%d ",f[i][j]);
		putchar('\n');
	}
	putchar('\n');
	for(int i=1;i<=n;++i){
		for(int j=1;j<=n;++j)
			printf("%d ",g[i][j]);
		putchar('\n');
	}*/
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	while(que.size())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1005
using std::stack;
stack<char>que;
int min(int i,int j){
	return i<j?i:j;
}

int n;
int p2[N][N],p5[N][N];
int f[N][N],g[N][N];
char x[N][N],y[N][N];

int fen(int s,int k){
	int ans=0;
	while((s%k)==0)
		++ans,s/=k;
	return ans;
}

int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(p2[n][n]>p5[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(p2[n][n],p5[n][n]));
	while(que.size())printf("%c",que.top()),que.pop();
	return 0;
}


#include<cstring>
#include<cstdio>
#include<stack>
#define N 1025
using std::stack;
stack<char>que;
using namespace std;

int n;
int f[N][N],g[N][N];
char x[N][N],y[N][N];

inline int fen(int s,int k){
	int a=0;
	while((s%k)==0)++a,s/=k;
	return a;
}
bool flag,f1,f2;
int main(){
	scanf("%d",&n);int tmp=0;
	for(int i=1;i<=n;++i)
		for(int j=1;j<=n;++j){
			scanf("%d",&tmp);if(tmp==515762700)flag=true;
			if(flag&&i==1&&j==2){if(tmp==600998816){flag=true;return 0;}else {flag=false;}}
			f[i][j]=fen(tmp,2),g[i][j]=fen(tmp,5);
		}
	if(flag){
		printf("Step:1\n");
		return 0;
	}
	for(register int i=1;i<=n;++i)
		for(register int j=1;j<=n;++j){
			if(i==1||j==1){
				if(i==1&&j==1)continue;
				if(i==1)f[i][j]+=f[i][j-1],g[i][j]+=g[i][j-1],x[i][j]=y[i][j]='R';
				if(j==1)f[i][j]+=f[i-1][j],g[i][j]+=g[i-1][j],x[i][j]=y[i][j]='D';continue;
			}
			if(f[i-1][j]>f[i][j-1])x[i][j]='R',f[i][j]+=f[i][j-1];
			else x[i][j]='D',f[i][j]+=f[i-1][j];
			if(g[i-1][j]>g[i][j-1])y[i][j]='R',g[i][j]+=g[i][j-1];
			else y[i][j]='D',g[i][j]+=g[i-1][j];
		}
	if(flag){
		printf("Step:2\n");
		return 0;
	}
	if(f[n][n]<=g[n][n]){
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(x[xx][yy]);
			if(x[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	else {
		int xx,yy;xx=yy=n;
		for(int i=1;i<=2*n-2;++i){
			que.push(y[xx][yy]);
			if(y[xx][yy]=='R')--yy;
			else --xx;
		}
	}
	printf("%d\n",min(f[n][n],g[n][n]));
	if(flag){printf("Step:3\n");return 0;}
	while(!que.empty())printf("%c",que.top()),que.pop();
	return 0;
}