The least possible number for q is ab+1.
Let Sp,q be the collection of small numbers, while Tp,q be the collection of big numbers. Write out Sp,q∪Tp,q in increasing order, and we get a sequence c1,…,ca+b−1 (note that clearly Sp,q∩Tp,q={1}). We claim that for each n≥2, if i,j<n are the maximum indices such that ci∈Sp,q, cj∈Tp,q, then cn=ci+cj, and furthermore cn∈Sp,q if and only if cipmodq>(−cjp)modq, in which case cnpmodq=(cipmodq)−(−cjpmodq).
We will show this by induction on n. When n=2 this is trivial. Now suppose that it holds for all indices smaller than n. By replacing p with −p, we can WLOG assume that cipmodq>(−cjp)modq.
If cn<ci+cj and cn∈Tp,q, then (−cnp)modq<(−cjp)modq, showing that 0<(cn−cj)pmodq<(−cjp)modq<cipmodq. Since cn−cj<ci, this contradicts the fact that ci∈Sp,q.
If cn<ci+cj and cn∈Sp,q, then we have cn−ci<cj and 0<−cncjpmodq<cipmodq. Let ck be the largest index smaller than cj that lies in Tp,q. Then it is clear that (−ckp)modq<cipmodq. If i<j, then by the inductive hypothesis, we have ci+1∈Sp,q, which contradicts the choice of i. Therefore i>j. Now let ℓ<j be the largest such that cℓ∈Sp,q. Then since ℓ<j<i, by the inductive hypothesis we have (−cjp)modq=(−ckpmodq)−(cℓpmodq)<(cipmodq)−(cipmodq)=0. This is a contradiction.
Therefore cn≥ci+cj. However, note that (ci+cj)modq=(cipmodq)−((−cjp)modq)<cipmodq, showing that ci+cj∈Sp,q and so cn=ci+cj.
Hence we can construct the sequence cn as follows: we first start with a red positive integer x and a blue positive integer y. Each time we choose the last red number and the last blue number and add them together, and color the number red or blue. We write m red numbers and n blue numbers in total. The situation above is when x=y=1,m=a−1,n=b−1 and red numbers are members of Sp,q, blue numbers are members of Tp,q. Let f(m,n,x,y) be the minimum possible total of the last written red number and the last written blue number. Since in the original setting, the last red number s and the last blue number t clearly satisfies spmodq=(−tp)modq=1 and so s+t=q, what we need to do is to give a lower bound of f(a,b,1,1). In fact, we can see that if m,n≥1, then
f(m,n,x,y)=min(f(m−1,n,x+y,y),f(m,n−1,x,x+y))
where the first term corresponds to coloring the next number red, and the second term corresponds to coloring the next number blue. We also have that f(m,0,x,y)=x+(m+1)y, f(0,n,x,y)=(n+1)x+y. Thus, we can induct on m+n and show that f(m,n,x,y)=mnmin(x,y)+(m+1)x+(n+1)y: suppose that it holds for all smaller m+n, then
f(m,n,x,y)=min((m−1)ny+m(x+y)+(n+1)y,m(n−1)x+(m+1)x+(n+1)(x+y))=mnmin(x,y)+(m+1)x+(n+1)y,
as desired. Thus, q≥f(a−1,b−1,1,1)=ab+1.
To show that it is possible that q=ab+1, pick p=a. Then Tp,q={1,2,…,b} and Sp,q={1,b+1,…,(a−1)b+1}.