https://codeforces.com/contest/2004/problem/D
题意:给定n个字符串,每个字符串有2个字符,如果两个字符串中有相同的字符,则这两个位置互相到达,到达的代价为坐标距离。并且所有字符串的种类只有6种,给定m个查询,求两个地方到达的最小代价。
思路:直接暴力,为6种字符串编号。如果查询位置上的字符串有相同字符,那可以直接算距离。如果没有相同字符,则检查距离l和r最近的其他4种字符串的位置,取代价最小的一个即可。
总结:感觉代码写复杂了
map<string, int> mapp{{"BG", 0}, {"BR", 1}, {"BY", 2}, {"GR", 3}, {"GY", 4}, {"RY", 5}};
void solve(){
int n, m;
cin >> n >> m;
vector<int> a(n);
vector<string> t(n);
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
t[i] = s;
a[i] = mapp[s];
}
vector<array<int, 6>> b(n + 1, {-1, -1, -1, -1, -1, -1});
for (int i = 0; i < n; ++i) {
b[i + 1] = b[i];
b[i + 1][a[i]] = i;
}
vector<array<int, 6>> c(n + 1, {-1, -1, -1, -1, -1, -1});
for (int i = n - 2; i >= 0; --i) {
c[i] = c[i + 1];
c[i][a[i + 1]] = i + 1;
}
while (m --) {
int l, r;
cin >> l >> r;
l --;
r --;
if (l > r) {
swap(l, r);
}
if (t[l][0] == t[r][0] || t[l][0] == t[r][1] || t[l][1] == t[r][0] || t[l][1] == t[r][1]) {
cout << r - l << '\n';
}
else {
int t1 = a[l];
int t2 = a[r];
bool ok = false;
for (int i = 0; i < 6; ++i) {
if (i != t1 && i != t2) {
if (b[l][i] != -1 || b[r][i] != -1 || c[l][i] != -1 || c[r][i] != -1) {
ok = true;
break;
}
}
}
if (!ok) {
cout << "-1\n";
}
else {
int res = (int)1e9;
for (int i = 0; i < 6; ++i) {
if (i != t1 && i != t2) {
if (b[l][i] != -1) {
res = min(res, abs(l - b[l][i]) + abs(r - b[l][i]));
}
if (c[l][i] != -1) {
res = min(res, abs(c[l][i] - l) + abs(r - c[l][i]));
}
if (c[r][i] != -1) {
res = min(res, abs(c[r][i] - l) + abs(c[r][i] - r));
}
if (b[r][i] != -1) {
res = min(res, abs(r - b[r][i]) + abs(l - b[r][i]));
}
}
}
cout << res << '\n';
}
}
}
}
标签:字符,Portals,Colored,int,cin,--,vector,字符串
From: https://www.cnblogs.com/yxcblogs/p/18369952