#include #include #include // for debug #define DEBUGw // ----------- #define NOP do{}while(0) #ifdef DEBUG #include #define TRACE(...) do{printf(__VA_ARGS__);fflush(stdout);}while(0) #define TRACECR do{putchar_unlocked('\n');fflush(stdout);}while(0) static clock_t startclock; void DEBUGSTART(void){TRACE("--DEBUG MODE --\n");startclock=clock();} void DEBUGEND(void){startclock=clock()-startclock;TRACE("--finish --\ntime is %.3fms\n",startclock/1000.);} #else #define TRACE(...) NOP #define TRACECR NOP void DEBUGSTART(void){return;} void DEBUGEND(void){return;} #endif extern int getchar_unlocked(void); extern int putchar_unlocked(int); #define PRINCR do{printf("\n");fflush(stdout);}while(0) #define GETLINE(str) do{char *p;fgets(str,sizeof(str),stdin);p=strchr(str,'\n');if(p)*p='\0';}while(0) #define REP(a,b) for(int a=0;a<(int)(b);++a) static char *GETWORD(char* str) {char c;char *cp;cp=&str[0];c=fgetc(stdin);while( c != EOF ){if((c==' ')||( c=='\n')) break;*cp++=c;c=fgetc(stdin);}*cp='\0';return &str[0];} #define GETINTS(a,b) {char s[34];int *ap=a;REP(i,b){GETWORD(s);sscanf(s,"%d", ap);ap++;}} static int GETLINEINT(void) {char s[34];GETLINE(s);return atoi(s);} static int GETWORDINT(void) {char s[34];GETWORD(s);return atoi(s);} #define SWAP(type,a,b) do{type _c;_c=a;a=b;b=_c;}while(0) int main() { int n, m; int i; long ll; int a[5001], b[5001]; int *ap,*bp; int wa,wb; scanf("%d%d\n", &n, &m); for (i = 0; i < n; i++) { a[i] = GETWORDINT(); TRACE("a[%d] = %d\n",i,a[i]); } for (i = 0; i < m; i++) { b[i] = GETWORDINT(); TRACE("b[%d] = %d\n",i,b[i]); } a[n] = b[m] = 99999; ap = &a[0]; bp = &b[0]; TRACE("start "); for (ll = 0L; ll < n * m; ll++) { if( 10000 < (wa = *ap++) ) { wa = a[0]; ap = &a[1]; } if( 10000 < (wb = *bp++) ) { wb = b[0]; bp = &b[1]; } TRACE("%d-%d ",wa,wb); if ( wa == wb ) { printf("%ld\n", ll+1); return 0; } } TRACE("End "); printf("-1\n"); return 0; }