Codeforces Round #659 (Div. 2) C. String Transformation 1(贪心,思维)

题目传送
题意:
给你俩个长度都为n的字符串a和b,现在每一次操作可以选定改变字符串a中的相同字符只要是相同的,都可以一起改变,或者选几个改变 ,但是只能变大,问你现在把a改变成b的最小操作数

思路:
首先明确一定,我们选择的字符串只能改大,不能改小。

1.所以当字符串a中的对应位置的字符大于b中的时候,直接输出-1

2.那么当排除不可能的情况后,我们怎么操作能使得操作数最小呢?这里我们记录下每个字符需要改变到的字符,如aaa -> bcd 那么a要改3种: a-> b ,a-> c,a-> d 。那么记录下有什么意义呢?我们知道只能改大,那么我们直接先把所有的a改成对应的最小字符也就是b ,这样的操作数会不会造成浪费呢?答案是不会的,还是那句话,我们只能改大,所以我们贪心,直接改成最小的那么现在就是bbb - > bcd,我们只用了一次操作次数,其他俩个a跟着改成了现在的最小我们不管他有没有到达他所对应的字符,反正我们现在就是顺便改一下,不会有什么影响那么我们依次这样,每次改成对应最小的,其他的都是顺便着改,这样是否正确呢?就因为一点,他只能改大,所以这个贪心原则就是对的

AC代码

#include <bits/stdc++.h>
inline long long read(){char c = getchar();long long x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 2e5 + 5;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const int mod = 1e9+7;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
signed main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    //    freopen("input.txt","r",stdin);
    //    freopen("output.txt","w",stdout);
    int t;
    cin >> t;
    while(t--)
    {
        int n,ans = 0;
        string a,b;
        set<int> s[26];//set去重
        cin >> n >> a >> b;
        a = " " + a;b = " " + b;
        for(int i = 1;i <= n;i++)
        {
            if(a[i] > b[i]) ans = 1;
            if(a[i] != b[i]) s[a[i]-'a'].insert(b[i]-'a');
        }
        if(ans) {cout << -1 << endl;continue;}//改不了
        for(int i = 0;i < 20;i++)
        {
            if(s[i].size() == 0) continue;
            int num = *s[i].begin();//改成最小
            s[i].erase(num);ans++;
            for(auto it:s[i])//把其他改后还没到达对应字符的字符加入到对应set中
                s[num].insert(it);
        }
        cout << ans << endl;
    }
}

猜你喜欢

转载自blog.csdn.net/moasad/article/details/107584124