poyo-poyo
9/24/2017 - 11:17 AM

ARC082-F Sandglass

ARC082-F Sandglass

void main(){
  import std.stdio, std.string, std.conv, std.algorithm;
  import std.typecons;
  
  int x, k;
  rd(x); rd(k);
  auto r=readln.split.to!(int[]);
  alias Q=Tuple!(int, "t", int, "a");
  auto qs=new Q[](0);
  foreach(t; r) qs~=Q(t, -1);
  int q; rd(q);
  foreach(_; 0..q){
    int t, a; rd(t, a);
    qs~=Q(t, a);
  }
 
  sort(qs);
  int p=0, l=0, u=x;
  int d=0, f=-1;
  foreach(e; qs){
    int dd=(e.t-p)*f;
    u=min(x, max(0, u+dd));
    l=max(0, min(x, l+dd));
    d+=dd; p=e.t;
    if(e.a==-1){// reverse
      f*=-1;
    }else{
      int y=e.a+d;
      writeln(min(u, max(l, y)));
    }
  }
}
 
void rd(T...)(ref T x){
  import std.stdio, std.string, std.conv;
  auto l=readln.split;
  foreach(i, ref e; x){
    e=l[i].to!(typeof(e));
  }
}