Problem:
Score : 1200 points

Problem Statement

In Takaha-shi, the capital of Republic of AtCoder, there are N roads extending east and west, and M roads extending north and south. There are no other roads.
The i-th east-west road from the north and the j-th north-south road from the west cross at the intersection (i, j).
Two east-west roads do not cross, nor do two north-south roads.
The distance between two adjacent roads in the same direction is 1.

Each road is one-way; one can only walk in one direction. The permitted direction for each road is described by a string S of length N and a string T of length M, as follows:

If the i-th character in S is W, one can only walk westward along the i-th east-west road from the north;

If the i-th character in S is E, one can only walk eastward along the i-th east-west road from the north;

If the i-th character in T is N, one can only walk northward along the i-th north-south road from the west;

If the i-th character in T is S, one can only walk southward along the i-th south-west road from the west.

Process the following Q queries:

In the i-th query, a_i, b_i, c_i and d_i are given. What is the minimum distance to travel to reach the intersection (c_i, d_i) from the intersection (a_i, b_i) by walking along the roads?

Constraints

2 \leq N \leq 100000

2 \leq M \leq 100000

2 \leq Q \leq 200000

|S| = N

S consists of W and E.

|T| = M

T consists of N and S.

1 \leq a_i \leq N

1 \leq b_i \leq M

1 \leq c_i \leq N

1 \leq d_i \leq M

(a_i, b_i) \neq (c_i, d_i)

Input

Input is given from Standard Input in the following format:

N M Q
S
T
a_1 b_1 c_1 d_1
a_2 b_2 c_2 d_2
:
a_Q b_Q c_Q d_Q

Output

In the i-th line, print the response to the i-th query. If the intersection (c_i, d_i) cannot be reached from the intersection (a_i, b_i) by walking along the roads, print -1 instead.

Sample Input 1

4 5 4
EEWW
NSNNS
4 1 1 4
1 3 1 2
4 2 3 2
3 3 3 5

Sample Output 1

6
11
5
4

The permitted direction for each road is shown in the following figure (north upward):

For each of the four queries, a route that achieves the minimum travel distance is as follows:

Sample Input 2

3 3 2
EEE
SSS
1 1 3 3
3 3 1 1

Sample Output 2

4
-1

The travel may be impossible.

Sample Input 3

9 7 10
EEEEEWEWW
NSSSNSN
4 6 9 2
3 7 6 7
7 5 3 5
1 1 8 1
4 3 5 4
7 4 6 4
2 5 8 6
6 6 2 7
2 4 7 5
7 2 9 7

Sample Output 3

9
-1
4
9
2
3
7
7
6
-1

Solution in Rust (1.15.1) (judge verdict: Accepted)

use contest::io::Scanner;
use std::collections::BinaryHeap;
use std::io::Write;

fn main() {
    let mut sc = Scanner::new(std::io::stdin());
    let n = sc.next::<usize>();
    let m = sc.next::<usize>();
    let q = sc.next::<usize>();
    let s = sc.next::<String>().chars().collect::<Vec<char>>();
    let t = sc.next::<String>().chars().collect::<Vec<char>>();

    let mut bottomLeft: Vec<i32> = vec![-1; n];
    let mut bottomRight: Vec<i32> = vec![-1; n];
    let mut upLeft: Vec<i32> = vec![-1; n];
    let mut upRight: Vec<i32> = vec![-1; n];
    for i in 0..n {
        if s[i] == 'W' {
            upLeft[i] = i as i32;
            if i > 0 {
                upRight[i] = upRight[i - 1];
            }
        } else {
            upRight[i] = i as i32;
            if i > 0 {
                upLeft[i] = upLeft[i - 1];
            }
        }
    }
    for i in (0..n).rev() {
        if s[i] == 'W' {
            bottomLeft[i] = i as i32;
            if i + 1 < n {
                bottomRight[i] = bottomRight[i + 1];
            }
        } else {
            bottomRight[i] = i as i32;
            if i + 1 < n {
                bottomLeft[i] = bottomLeft[i + 1];
            }
        }
    }

    let mut leftUp: Vec<i32> = vec![-1; m];
    let mut leftDown: Vec<i32> = vec![-1; m];
    let mut rightUp: Vec<i32> = vec![-1; m];
    let mut rightDown: Vec<i32> = vec![-1; m];
    for i in 0..m {
        if t[i] == 'N' {
            leftUp[i] = i as i32;
            if i > 0 {
                leftDown[i] = leftDown[i - 1];
            }
        } else {
            leftDown[i] = i as i32;
            if i > 0 {
                leftUp[i] = leftUp[i - 1];
            }
        }
    }
    for i in (0..m).rev() {
        if t[i] == 'N' {
            rightUp[i] = i as i32;
            if i + 1 < m {
                rightDown[i] = rightDown[i + 1];
            }
        } else {
            rightDown[i] = i as i32;
            if i + 1 < m {
                rightUp[i] = rightUp[i + 1];
            }
        }
    }

    for _ in 0..q {
        let a = sc.next::<usize>() - 1;
        let b = sc.next::<usize>() - 1;
        let c = sc.next::<usize>() - 1;
        let d = sc.next::<usize>() - 1;

        let mut rows: Vec<(i32, char)> = vec![];
        let mut cols: Vec<(i32, char)> = vec![];

        push(&mut rows, (upRight[a], 'R'));
        push(&mut rows, (upRight[a], 'R'));
        push(&mut rows, (upRight[c], 'R'));
        push(&mut rows, (bottomRight[a], 'R'));
        push(&mut rows, (bottomRight[c], 'R'));
        push(&mut rows, (upLeft[a], 'L'));
        push(&mut rows, (upLeft[c], 'L'));
        push(&mut rows, (bottomLeft[a], 'L'));
        push(&mut rows, (bottomLeft[c], 'L'));

        push(&mut cols, (leftUp[b], 'U'));
        push(&mut cols, (leftUp[d], 'U'));
        push(&mut cols, (rightUp[b], 'U'));
        push(&mut cols, (rightUp[d], 'U'));
        push(&mut cols, (leftDown[b], 'D'));
        push(&mut cols, (leftDown[d], 'D'));
        push(&mut cols, (rightDown[b], 'D'));
        push(&mut cols, (rightDown[d], 'D'));

        rows.sort();
        cols.sort();

        rows.dedup();
        cols.dedup();

        let mut startX = 10;
        let mut startY = 10;
        let mut goalX = 10;
        let mut goalY = 10;
        for i in 0..rows.len() {
            if rows[i].0 == a as i32 {
                startX = i;
            }
            if rows[i].0 == c as i32 {
                goalX = i;
            }
        }
        for i in 0..cols.len() {
            if cols[i].0 == b as i32 {
                startY = i;
            }
            if cols[i].0 == d as i32 {
                goalY = i;
            }
        }
        // println!("sX sY gX gY: {} {} {} {}", startX, startY, goalX, goalY);

        let inf = 1_000_000_000 as i32;
        let mut dist = vec![vec![inf; 8]; 8];
        let mut q = BinaryHeap::new();
        q.push((inf - 0, startX, startY));
        while !q.is_empty() {
            let (dd, x, y) = q.pop().unwrap();
            // println!("q.pop: {} {} {}", inf - dd, x, y);
            if dist[x][y] < inf {
                continue;
            }
            dist[x][y] = inf - dd;
            if rows[x].1 == 'L' {
                if y > 0 {
                    let d = cols[y].0 - cols[y - 1].0;
                    q.push((dd - d, x, y - 1));
                }
            } else {
                if y + 1 < cols.len() {
                    let d = cols[y + 1].0 - cols[y].0;
                    q.push((dd - d, x, y + 1));
                }
            }
            if cols[y].1 == 'U' {
                if x > 0 {
                    let d = rows[x].0 - rows[x - 1].0;
                    q.push((dd - d, x - 1, y));
                }
            } else {
                if x + 1 < rows.len() {
                    let d = rows[x + 1].0 - rows[x].0;
                    q.push((dd - d, x + 1, y));
                }
            }
        }
        // write!(std::io::stderr(), "{:?}\n", rows);
        // write!(std::io::stderr(), "{:?}\n", cols);
        // write!(std::io::stderr(), "{:?}\n", dist);
        let mut res = dist[goalX][goalY];
        if res == inf {
            println!("-1");
        } else {
            println!("{}", res);
        }
    }
}

fn push(rows: &mut Vec<(i32, char)>, (x, d): (i32, char)) {
    if x >= 0 {
        rows.push((x, d));
    }
}
pub mod contest {
    pub mod io {
        /// Scanner
        ///
        /// # Example
        /// ```
        /// use contest::io::Scanner;
        /// let mut sc = Scanner::new("1 2 \n\n \r\t \n 3.5".as_bytes());
        /// assert_eq!("1".to_string(), sc.next::<String>());
        /// assert_eq!(2, sc.next());
        /// assert_eq!(3.5, sc.next());
        ///
        /// // To create a scanner from stdin:
        /// Scanner::new(std::io::stdin());
        /// ```
        use std;
        use std::io;
        use std::io::BufRead;

        pub struct Scanner<R: io::Read> {
            br: io::BufReader<R>,
            // Read tokens are stored in reversed order per line.
            buf: Vec<String>,
        }

        pub fn new<R: io::Read>(r: R) -> Scanner<R> {
            Scanner::new(r)
        }

        impl<R: io::Read> Scanner<R> {
            #[inline]
            pub fn new(r: R) -> Scanner<R> {
                Scanner {
                    br: io::BufReader::new(r),
                    buf: vec![],
                }
            }
            #[inline]
            pub fn next<T>(&mut self) -> T
            where
                T: std::str::FromStr,
                T::Err: std::fmt::Debug,
            {
                self.next_string()
                    .map(|s| s.parse::<T>().expect("Parse failed: "))
                    .expect("Unexpected EOF")
            }
            #[inline]
            pub fn next2<T1, T2>(&mut self) -> (T1, T2)
            where
                T1: std::str::FromStr,
                T2: std::str::FromStr,
                T1::Err: std::fmt::Debug,
                T2::Err: std::fmt::Debug,
            {
                (self.next(), self.next())
            }
            fn next_string(&mut self) -> Option<String> {
                self.buf.pop().or_else(|| match self.update() {
                    true => self.next_string(),
                    false => None,
                })
            }
            #[inline]
            fn update(&mut self) -> bool {
                let mut s = String::new();
                let res = self.br.read_line(&mut s);
                match res.expect("I/O error.") {
                    0 => false,
                    _ => {
                        self.buf = s.split_whitespace().map(|x| x.to_string()).rev().collect();
                        true
                    }
                }
            }
        }

        #[test]
        fn test_next() {
            let mut sc = new("hoge".as_bytes());
            let s: String = sc.next();
            assert_eq!("hoge", s);
        }
    }
}