https://codeforces.com/problemset/problem/1383/A
- 并查集 :https://blog.csdn.net/jziwjxjd/article/details/107603759
- 拓扑排序 :https://blog.csdn.net/weixin_45817880/article/details/107573083
- 优先队列 :
#include<bits/stdc++.h>
#define ios std::ios::sync_with_stdio(false)
#define rep(i,a,n) for (int i=a;i<=n;i++)
using namespace std;
const int N = 2e5 + 10;
int T,n,ans;
char s1[N],s2[N];
struct node{
char c;
int w;
bool operator<(const node& A)const{
if (c == A.c) return w > A.w;
else return c > A.c;
}
};
int main()
{
cin >> T;
while (T--){
priority_queue<node>q;
ans = 0;
cin >> n;
cin >> s1 >> s2;
int flag = 0;
rep(i,0,n-1){
if (s1[i] < s2[i]){
q.push({s1[i],s2[i]-s1[i]});
}
else if (s1[i] > s2[i]){
cout << "-1\n";
flag = 1;
break;
}
}
if (flag) continue;
while(!q.empty()){
node tmp = q.top();
q.pop();
while (!q.empty() && tmp.c == q.top().c && tmp.w == q.top().w) q.pop();
if (q.empty()||tmp.c != q.top().c) ans++;
else{
while(!q.empty()&&tmp.c == q.top().c){
q.push({(char)(tmp.c+tmp.w),q.top().w-tmp.w});
q.pop();
}
ans++;
}
}
cout << ans << "\n";
}
return 0;
}