Swap Letters

题目链接http://codeforces.com/contest/1215/problem/C

给你两个相同长度的字符串,可以第一个字符串的i下标和第二个字符串的j坐标的两个位置的字符进行交换,问能否把两个字符串更改为相同的字符串,若能输出最小操作次数,并分别输出两个字符串要更改的下班,否则输出-1

比如下图这种情况,最佳的交换方式是一定的。所以只需要在第一个串中统计s[i]!=t[i]且s[i]='a'的位置,计数cnt1,每两个为一组按照下图的交换方式交换。同理也需要统计s[i]!=t[i]且s[i]='b'的位置,计数cnt2,处理方法同上。

注意:如cnt1和cnt2都为奇数的,那么处理完后会剩下下图这种情况,处理方法如下:

交换方法:==》==》

如果cnt1 /cnt2中只有一个为奇数的话,无解。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5+10;
vector<int> a, b;//只记录s串中不对应的a和b的位置
char s[maxn],t[maxn];
int main()
{
    //freopen("/Users/zhangkanqi/Desktop/11.txt","r",stdin);
    int n;
    scanf("%d", &n);
    scanf("%s", s+1);
    scanf("%s", t+1);
    for(int i = 1; i <= n; i++)
    {
        if(s[i] != t[i])
        {
            if(s[i] == 'a') a.push_back(i);
            else b.push_back(i);
        }
    }
    if( (a.size() + b.size()) & 1)  puts("-1");
    else
    {
        int cnt = a.size() / 2 + b.size() / 2;
        if((a.size()&1) && (b.size()&1)) cnt += 2;
        printf("%d
", cnt);
        for(int i = 0; i+1 < a.size(); i += 2)
            printf("%d %d
", a[i], a[i+1]);
        for(int i = 0; i+1 < b.size(); i += 2)
            printf("%d %d
", b[i], b[i+1]);
        if((a.size()&1) && (b.size()&1))
        {
            printf("%d %d
", a[a.size()-1], a[a.size()-1]);
            printf("%d %d
", a[a.size()-1], b[b.size()-1]);
        }
    }
}
原文地址:https://www.cnblogs.com/shmilky/p/14089018.html