The page width is fixed to W characters. In order to make the article look more beautiful, Yellowstar has made some rules:
1. The fixed width of the picture is pw. The distance from the left side of the page to the left side of the photo fixed to dw, in other words, the left margin is dw, and the right margin is W - pw - dw.
2. The photo and words can't overlap, but can exist in same line.
3. The relative order of words cannot be changed.
4. Individual words need to be placed in a line.
5. If two words are placed in a continuous position on the same line, then there is a space between them.
6. Minimize the number of rows occupied by the article according to the location and height of the image.
However, Yellowstar has not yet determined the location of the picture and the height of the picture, he would like to try Q different locations and different heights to get the best look. Yellowstar tries too many times, he wants to quickly know the number of rows each time, so he asked for your help. It should be noted that when a row contains characters or pictures, the line was considered to be occupied.
Each case begins with one line with four integers N, W, pw, dw : the number of words, page width, picture width and left margin.
The next line contains N integers ai, indicates i-th word consists of ai characters.
The third line contains one integer Q.
Then Q lines follow, each line contains the values of xi and hi, indicates the starting line and the image height of the image.
Limits
T≤10
1≤N,W,Q≤105
1≤pw,ai≤W
0≤dw≤W−pw
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int N=1e5+;
int n,w,pw,dw;
int a[N];
int lto[N],rto[N],to[N];
int s[N][],t[N][]; void cal(int *c,int W)
{
int len=-;
for(int i=,j=;i<=n;i++)
{
while(len+a[j]+<=W) len+=a[j]+,j++;
c[i]=j;
len-=a[i]+;
}
}
void process()
{
cal(lto,w);
for(int i=;i<=n;i++) s[i][]=lto[i];
to[n]=;
for(int i=n-;i>=;i--) to[i]=to[lto[i]]+;
for(int i=;i<;i++)
for(int j=;j<=n;j++)
s[j][i]=s[s[j][i-]][i-];
cal(lto,dw);
cal(rto,w-dw-pw);
for(int i=;i<=n;i++) t[i][]=rto[lto[i]];
for(int i=;i<;i++)
for(int j=;j<=n;j++)
t[j][i]=t[t[j][i-]][i-];
}
int main()
{
int T; cin>>T;
while(T--)
{
scanf("%d%d%d%d",&n,&w,&pw,&dw);
for(int i=;i<n;i++) scanf("%d",&a[i]);
a[n]=w+;
process();
int Q; scanf("%d",&Q);
while(Q--)
{
int x,h,ans,tot=; scanf("%d%d",&x,&h);
ans=min(--x,to[]);
for(int i=,tmp=ans;i<;i++)
{
if(tmp&) tot=s[tot][i];
tmp>>=;
}
for(int i=,tmp=h;i<;i++)
{
if(tmp&) tot=t[tot][i];
tmp>>=;
}
ans+=h;
ans+=to[tot];
printf("%d\n",ans);
}
}
return ;
}