-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfenwick_tree.cpp
More file actions
76 lines (68 loc) · 1.6 KB
/
Copy pathfenwick_tree.cpp
File metadata and controls
76 lines (68 loc) · 1.6 KB
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
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define mod (int)(1e9+7)
#define inf (int)(1e18)
#define sz(s) (int)s.size()
#define all(v) (v).begin(),(v).end()
#define fill(v,p) memset(v,p,sizeof(v))
#define input(vec) for (auto &el : vec) cin >> el;
#define print(vec) for (auto &el : vec) cout << el << " "; cout << "\n";
struct BIT {
vector<int>tree;
int n;
BIT(int n) {
this->n = n;
tree.resize(n);
}
int query(int r) {
int res = 0;
while(r>=0) {
res += tree[r];
r = (r&(r+1))-1;
}
return res;
}
void update(int i,int val) {
while(i<n) {
tree[i] += val;
i = (i|(i+1));
}
}
};
void solve() {
int n;
cin>>n;
BIT T(n);
for(int i=0;i<n;i++) {
T.update(i,1);
}
string s,t;
cin>>s>>t;
queue<int>q[26];
for(int i=0;i<n;i++) {
q[s[i]-'a'].push(i);
}
int ans = inf,calc=0;
for(int i=0;i<n;i++) {
int cur = inf;
for(int j=0;j<(int)(t[i]-'a');j++) {
if(q[j].empty()) continue;
cur = min(cur,T.query(q[j].front()));
}
if(cur<inf) ans = min(ans,calc+cur-1LL);
if(q[t[i]-'a'].empty()) break;
calc += T.query(q[t[i]-'a'].front())-1LL;
T.update(q[t[i]-'a'].front(),-1);
q[t[i]-'a'].pop();
}
cout<<(ans==inf ? -1 : ans)<<"\n";
}
signed main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);cout.tie(nullptr);
int testcases=1;
cin>>testcases;
while(testcases--) solve();
return 0;
}