program sample
    implicit none
    character(1),allocatable::dis(:)
    integer(8) :: i,j,m,n,uc,rc,dc,lc,acci,a
    integer(8),allocatable :: x(:),y(:),ux(:),uy(:),rx(:),ry(:),dx(:),dy(:),lx(:),ly(:)
  
    read(*,*) n
    allocate(x(n),y(n),dis(n),ux(n),uy(n),rx(n),ry(n),dx(n),dy(n),lx(n),ly(n))
    do i=1,n
        read(*,*)x(i),y(i),dis(i)
    end do
    uc=0
    rc=0
    dc=0
    lc=0
    do i=1,n
        if(dis(i) .eq. 'U')then
            uc=uc+1
            ux(uc)=x(i)
            uy(uc)=y(i)
        
        elseif(dis(i) .eq. 'R')then
                rc=rc+1
                rx(rc)=x(i)
                ry(rc)=y(i)
        elseif(dis(i) .eq. 'D')then
                    dc=dc+1
                    dx(dc)=x(i)
                    dy(dc)=y(i)
        elseif(dis(i) .eq. 'L')then
                        lc=lc+1
                        lx(lc)=x(i)
                        ly(lc)=y(i)
        end if
    end do
    acci=10**8
    do i=1,uc
        do j=1,dc
            if(ux(i)==dx(j) .and. uy(i)<dy(j))then
                a=(dy(j)-uy(i))*5
                if(acci>a)then
                    acci=a
                end if
            end if
        end do
    end do
    do i=1,uc
        do j=1,rc
            if(ux(i)-rx(j)>0 .and. ux(i)-rx(j)==ry(j)-uy(i))then
                a=(ux(i)-rx(j))*10
                if(acci>a)then
                    acci=a
                end if
            end if
        end do
    end do
    do i=1,uc
        do j=1,lc
            if(lx(j)-ux(i)>0 .and. lx(j)-ux(i)==ly(j)-uy(i))then
                a=(lx(j)-ux(i))*10
                if(acci>a)then
                    acci=a
                end if
            end if
        end do
    end do
    do i=1,rc
        do j=1,dc
            if(dx(j)-rx(i)>0 .and. dx(j)-rx(i)==dy(j)-ry(i))then
                a=(dx(j)-rx(i))*10
                if(acci>a)then
                    acci=a
                end if
            end if
        end do
    end do

    do i=1,rc
        do j=1,lc
            if(ry(i)==ly(j) .and. ly(j)>ry(i))then
                a=(ly(j)-ry(i))*5
                if(acci>a)then
                    acci=a
                end if
            end if
        end do
    end do
    do i=1,dc
        do j=1,lc
            if(lx(j)-dx(i)>0 .and. lx(j)-dx(i)==dy(i)-ly(j))then
                a=(lx(j)-dx(i))*10
                if(acci>a)then
                    acci=a
                end if
            end if
        end do
    end do
    if(acci==10**8)then
        write(*,*)'SAFE'
    else
        write(*,*)acci
    end if
  
    stop
end program sample
  

