void main(){
  import std.stdio, std.string, std.conv, std.algorithm;
  
  int n; rd(n);
  auto m=new int[](n), d=new int[](n);
  auto v=new int[](n), s=new int[](n);
  foreach(i; 0..n) rd(m[i], d[i], v[i], s[i]);
  
  int f(int v){
    return (v-1)%360+1;
  }
  
  auto days=new int[](361);
  foreach(i; 0..n){
    int st=(m[i]-1)*30+d[i];
    int ed=st+v[i]-1;
    foreach(_; 0..3){
      foreach(x; 1..1500){
        if(x<st){
          chmax(days[f(x)], max(0, s[i]-(st-x)));
        }else if(st<=x && x<=ed){
          chmax(days[f(x)], s[i]);
        }else{// ed<x
          chmax(days[f(x)], max(0, s[i]-(x-ed)));
        }
      }
      st+=360; ed+=360;
    }
  }
  
  days[0]=100100100;
  writeln(reduce!(min)(days));
}

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));
  }
}

void chmax(T1, T2)(ref T1 x, T2 y){
  if(x<y) x=y;
}