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
| #include <bits/stdc++.h> #define rep(i, x, y) for (int i = x; i <= y; i++) using namespace std;
const int N = 1e5 + 10; int T, n, num[30][30]; char a[N], b[N];
int main() { cin >> T; while (T--) { cin >> n; scanf("%s%s", a + 1, b + 1); bool ff = 1; rep(i, 1, n) if (a[i] > b[i]) { ff = 0; break; } if (!ff) { puts("-1"); continue; } memset(num, 0, sizeof(num)); rep(i, 1, n) { if (a[i] != b[i]) num[a[i] - 'a'][b[i] - 'a']++; } int ans = 0; rep(i, 0, 25) { rep(j, i + 1, 25) { if (num[i][j]) { ++ans; num[i][j] = 0; rep(k, j + 1, 25) { if (num[i][k]) { num[j][k] += num[i][k], num[i][k] = 0; } } } } } printf("%d\n", ans); } return 0; }
|