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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
| #include <iostream> #include <string> #include <algorithm> #include <functional> #include <vector> #include <stack> #include <queue> #include <set> #include <map> #include <cstdio> #include <cmath> #include <tuple> #include <random> #include <cassert> #include <unordered_map> #define rep(i, n) for(i = 0; i < n; i++) #define int long long using namespace std;
mt19937 mt(2521);
int naive(string s) { queue<string> que; unordered_map<string, int> dp; map<string, string> prevS; vector<vector<int>> perms = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, {1, 2, 0}, {2, 0, 1}, {2, 1, 0}};
que.push(s); dp[s] = 0; int ret = -1; string ret_s; while (!que.empty()) { string now = que.front(); que.pop(); int n = now.length();
bool check = true; for (int i = 0; i < n - 1; i++) { if (now[i] != now[i + 1]) { check = false; break; } } if (check) { ret = dp[now]; ret_s = now; break; }
for (int i = 0; i < 6; i++) { for (int l = 0; l < n; l++) { string t; for (int r = l; r < n; r++) { int x = perms[i][now[r] - 'A']; t += (char)(x + 'A'); string nxt; for (int k = 0; k < l; k++) nxt += now[k]; nxt += t; for (int k = r + 1; k < n; k++) nxt += now[k]; if (dp.find(nxt) == dp.end()) { dp[nxt] = dp[now] + 1; prevS[nxt] = now; que.push(nxt); } } } } }
return ret; }
int greedy(string s) { int i; string ss; rep(i, s.length()) { if (i > 0 && s[i - 1] == s[i]) continue; ss += s[i]; }
int ret = ss.length(); int n = ss.length(); typedef pair<int, char> P; for (char c = 'A'; c <= 'C'; c++) { vector<P> vec; int len = 0; char first_char = '-';
rep(i, n) { if (ss[i] == c) { if (len > 0) vec.push_back(P(len, first_char)); len = 0; continue; } if (len == 0) first_char = ss[i]; len++; } if (len > 0) vec.push_back(P(len, first_char));
int cst = 0;
rep(i, vec.size()) { cst += vec[i].first / 2 + 1; }
int cnt = 0; for (int i = 0; i < vec.size(); i++) { if (vec[i].first % 2 == 0) cnt++; } cst -= cnt / 2; ret = min(ret, cst); } return ret; }
void solve_input() { int n, Q; cin >> n >> Q; string s; cin >> s; for (int i = 0; i < Q; i++) { int l, r; cin >> l >> r; l--; r--;
string t; for (int j = l; j <= r; j++) t += s[j]; cout << greedy(t) << endl; } }
signed main() { solve_input(); return 0;
}
|