-
Notifications
You must be signed in to change notification settings - Fork 0
/
2004D.cpp
100 lines (85 loc) · 1.67 KB
/
2004D.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <iostream>
#include <map>
#include <string>
#include <vector>
using namespace std;
vector<string> colors = { "BG", "BR", "BY", "GR", "GY", "RY" };
map<string, int> clrid;
void solve()
{
int n, q;
cin >> n >> q;
vector<string> c(n);
for (int i = 0; i < n; i++)
cin >> c[i];
vector<vector<int> > cities(colors.size());
for (int i = 0; i < n; i++)
cities[clrid[c[i]]].push_back(i);
for (int qn = 0; qn < q; qn++)
{
int x, y;
cin >> x >> y;
x--, y--;
if (x > y)
swap(x, y);
int ans = -1;
if (c[x][0] == c[y][0] ||
c[x][0] == c[y][1] ||
c[x][1] == c[y][0] ||
c[x][1] == c[y][1])
ans = abs(x - y);
else
{
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
string s = c[x];
s[i] = c[y][j];
int z = clrid[s];
if (cities[z].empty())
continue;
int k = lower_bound(cities[z].begin(), cities[z].end(), x) - cities[z].begin();
if (k < cities[z].size() && cities[z][k] < y)
{
int d = abs(x - y);
if (ans < 0 || ans > d)
ans = d;
}
else
{
if (k > 0)
{
int d = abs(x - cities[z][k - 1]) + abs(cities[z][k - 1] - y);
if (ans < 0 || ans > d)
ans = d;
}
if (k < cities[z].size())
{
int d = abs(x - cities[z][k]) + abs(cities[z][k] - y);
if (ans < 0 || ans > d)
ans = d;
}
}
}
}
}
cout << ans << endl;
}
}
int main()
{
ios::sync_with_stdio(false);
for (int i = 0; i < colors.size(); i++)
{
clrid[colors[i]] = i;
string tmp = colors[i];
swap(tmp[0], tmp[1]);
clrid[tmp] = i;
}
int t;
cin >> t;
for (int tn = 0; tn < t; tn++)
solve();
return 0;
}