2004D.md (1848B)
1 Source: https://codeforces.com/problemset/problem/2004/D 2 3 D. Colored Portals 4 5 time limit per test 6 7 2 seconds 8 9 memory limit per test 10 11 256 megabytes 12 13 input 14 15 standard input 16 17 output 18 19 standard output 20 21 There are $n$ cities located on a straight line. The cities are numbered from $1$ to $n$. 22 23 Portals are used to move between cities. There are $4$ colors of portals: blue, green, red, and yellow. Each city has portals of two different colors. You can move from city $i$ to city $j$ if they have portals of the same color (for example, you can move between a "blue-red" city and a "blue-green" city). This movement costs $|i-j|$ coins. 24 25 Your task is to answer $q$ independent queries: calculate the minimum cost to move from city $x$ to city $y$. 26 27 Input 28 29 The first line contains a single integer $t$ ($1 \le t \le 10^4$) — the number of test cases. 30 31 The first line of each test case contains two integers $n$ and $q$ ($1 \le n, q \le 2 \cdot 10^5$) — the number of cities and the number of queries, respectively. 32 33 The second line contains $n$ strings of the following types: BG, BR, BY, GR, GY, or RY; the $i$-th of them describes the portals located in the $i$-th city; the symbol B indicates that there is a blue portal in the city, G — green, R — red, and Y — yellow. 34 35 The $j$-th of the next $q$ lines contains two integers $x_j$ and $y_j$ ($1 \le x_j, y_j \le n$) — the description of the $j$-th query. 36 37 Additional constraints on the input: 38 39 * the sum of $n$ over all test cases does not exceed $2 \cdot 10^5$; 40 * the sum of $q$ over all test cases does not exceed $2 \cdot 10^5$. 41 42 Output 43 44 For each query, print a single integer — the minimum cost to move from city $x$ to city $y$ (or $-1$ if it is impossible). 45 46 Example 47 48 Input 49 50 ``` 51 2 52 53 4 5 54 55 BR BR GY GR 56 57 1 2 58 59 3 1 60 61 4 4 62 63 1 4 64 65 4 2 66 67 2 1 68 69 BG RY 70 71 1 2 72 ``` 73 74 Output 75 76 ``` 77 1 78 4 79 0 80 3 81 2 82 -1 83 ```