1
+ /* *
2
+ * @file 105631F.cpp
3
+ * @author Macesuted ([email protected] )
4
+ * @date 2025-01-03
5
+ *
6
+ * @copyright Copyright (c) 2025
7
+ *
8
+ */
9
+
10
+ #include < bits/stdc++.h>
11
+ using namespace std ;
12
+
13
+ #ifndef LOCAL
14
+ #define endl ' \n '
15
+ #endif
16
+
17
+ bool mem1;
18
+
19
+ string a;
20
+ bool chk[27 ];
21
+ int cnt[27 ], len[27 ], nxt[27 ][27 ], jmp[27 ];
22
+
23
+ void dfs (int p) {
24
+ if (jmp[p] >= 0 )
25
+ dfs (jmp[p]), len[p] = len[jmp[p]] + 1 ;
26
+ else
27
+ len[p] = (chk[p] ? 1 : -1 );
28
+ return ;
29
+ }
30
+
31
+ void solve (void ) {
32
+ int n;
33
+ cin >> n >> a, a = ' ' + a;
34
+ for (int i = 1 ; i <= n; i++) cnt[a[i] - ' a' ]++;
35
+ for (int i = 1 ; i < n; i++) nxt[a[i] - ' a' ][a[i + 1 ] - ' a' ]++;
36
+
37
+ int q;
38
+ cin >> q;
39
+ while (q--) {
40
+ int pos;
41
+ char c;
42
+ cin >> pos >> c;
43
+
44
+ cnt[a[pos] - ' a' ]--;
45
+ if (pos > 1 ) nxt[a[pos - 1 ] - ' a' ][a[pos] - ' a' ]--;
46
+ if (pos < n) nxt[a[pos] - ' a' ][a[pos + 1 ] - ' a' ]--;
47
+ a[pos] = c;
48
+ if (pos > 1 ) nxt[a[pos - 1 ] - ' a' ][a[pos] - ' a' ]++;
49
+ if (pos < n) nxt[a[pos] - ' a' ][a[pos + 1 ] - ' a' ]++;
50
+ cnt[a[pos] - ' a' ]++;
51
+
52
+ int mx = 0 ;
53
+ for (int i = 0 ; i < 26 ; i++) mx = max (mx, cnt[i]);
54
+ for (int i = 0 ; i < 26 ; i++) {
55
+ jmp[i] = -1 ;
56
+ if (cnt[i] < mx || a[n] - ' a' == i) continue ;
57
+ for (int j = 0 ; j < 26 ; j++)
58
+ if (nxt[i][j] > 0 ) {
59
+ if (jmp[i] == -1 )
60
+ jmp[i] = j;
61
+ else
62
+ jmp[i] = -2 ;
63
+ }
64
+ if (jmp[i] >= 0 && cnt[jmp[i]] < mx) jmp[i] = -1 ;
65
+ }
66
+ for (int i = 0 ; i < 26 ; i++) chk[i] = (cnt[i] == mx), len[i] = 0 ;
67
+ for (int i = 0 ; i < 26 ; i++)
68
+ if (!len[i]) dfs (i);
69
+ int ans = 0 , mxlen = 0 ;
70
+ for (int i = 0 ; i < 26 ; i++)
71
+ if (len[i] > 0 ) ans += len[i], mxlen = max (mxlen, len[i]);
72
+ cout << 3 * ans - mxlen << endl;
73
+ }
74
+ return ;
75
+ }
76
+
77
+ bool mem2;
78
+
79
+ int main () {
80
+ ios::sync_with_stdio (false ), cin.tie (nullptr );
81
+ #ifdef LOCAL
82
+ cerr << " Memory Cost: " << abs (&mem1 - &mem2) / 1024 . / 1024 . << " MB" << endl;
83
+ #endif
84
+
85
+ int _ = 1 ;
86
+ while (_--) solve ();
87
+
88
+ #ifdef LOCAL
89
+ cerr << " Time Cost: " << clock () * 1000 . / CLOCKS_PER_SEC << " MS" << endl;
90
+ #endif
91
+ return 0 ;
92
+ }
0 commit comments