Codeforces Round #501 (Div. 3) B. Obtaining the String (思维,字符串)

  • 题意:有两个字符串\(S\)\(T\),判断\(T\)是否能由\(S\)通过交换某位置的相邻字符得到,如果满足,输出交换次数及每次交换的位置,否则输出\(-1\).

  • 题解:首先判断不满足的情况,只有当两个字符串中出现的字母次数不同时不满足条件,用桶判断一下即可.然后我们再来看有解的情况,我们对\(T\)的每个字符标上序号,如样例1中:\(abdfec\)对应\(123456\),则\(S\)中与之对应的是\(abcdef\)->\(126354\),所以要想让\(S\)变成\(T\),就要让其序号变成\(T\)的序号,我们冒泡排序记录变换位置就能的出答案.

  • 代码:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cmath>
    #include <algorithm>
    #include <stack>
    #include <queue>
    #include <vector>
    #include <map>
    #include <set>
    #include <unordered_set>
    #include <unordered_map>
    #define ll long long
    #define fi first
    #define se second
    #define pb push_back
    #define me memset
    const int N = 1e6 + 10;
    const int mod = 1e9 + 7;
    const int INF = 0x3f3f3f3f;
    using namespace std;
    typedef pair<int,int> PII;
    typedef pair<ll,ll> PLL;
     
    int n;
    string s,t;
    int num[N];
    vector<int> ans;
    map<char,int> mp1,mp2;
     
    int main() {
        ios::sync_with_stdio(false);cin.tie(0);
        cin>>n;
        cin>>s>>t;
        for(int i=0;i<s.size();++i){
            mp1[s[i]]++;
        }
        for(int i=0;i<t.size();++i){
            mp2[t[i]]++;
        }
        for(char i='a';i<='z';++i){
            if(mp1[i]!=mp2[i]){
                puts("-1");
                return 0;
            }
        }
        for(int i=0;i<n;++i){
            for(int j=0;j<n;++j){
                if(s[j]==t[i] && num[j]==0){
                    num[j]=i;
                    break;
                }
            }
        }
        for(int i=0;i<n;++i){
            for(int j=0;j<n-1;++j){
                if(num[j]>num[j+1]){
                    ans.pb(j+1);
                    swap(num[j],num[j+1]);
                }
            }
        }
        printf("%zu\n",ans.size());
        for(auto w:ans){
            printf("%d ",w);
        }
     
        return 0;
    }
    
原文地址:https://www.cnblogs.com/lr599909928/p/13091977.html