【題解】Codeforces 1384C. String Transformation 1

【題目敘述】http://codeforces.com/contest/1384/problem/C

#include <iostream>
#include <cstring>
using namespace std;
 
int t, n, x, y, p[25], ans;
string a, b;
 
int f(int x){
    if (p[x] < 0) return x;
    else return p[x] = f(p[x]);
}
 
int main() {
    cin >> t;
    while (t--){
        cin >> n;
        cin >> a >> b;
        bool flag = true;
        for (int i = 0; i < 20; i++){
            p[i] = -1;
        }
        for (int i = 0; i < n; i++){
            x = a[i]-'a';
            y = b[i]-'a';
            if (x > y){
                flag = false;
                break;
            }
            else if (x < y && f(x) != f(y)){
                p[f(x)] += p[f(y)];
                p[f(y)] = f(x);
            }
        }
        if (!flag){
            cout << -1 << "\n";
            continue;
        }
        ans = 0;
        for (int i = 0; i < 20; i++){
            if (p[i] < 0) ans -= p[i]+1;
        }
        cout << ans << "\n";
    }
}
分享本文 Share with friends