题目地址:https://codeforces.com/contest/1215/problem/C
题目:
Monocarp has got two strings ?s and ?t having equal length. Both strings consist of lowercase Latin letters "a" and "b".
Monocarp wants to make these two strings ?s and ?t equal to each other. He can do the following operation any number of times: choose an index ???1pos1 in the string ?s, choose an index ???2pos2 in the string ?t, and swap ????1spos1 with ????2tpos2.
You have to determine the minimum number of operations Monocarp has to perform to make ?s and ?t equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.
Input
The first line contains one integer ?n (1≤?≤2⋅105)(1≤n≤2⋅105) — the length of ?s and ?t.
The second line contains one string ?s consisting of ?n characters "a" and "b".
The third line contains one string ?t consisting of ?n characters "a" and "b".
Output
If it is impossible to make these strings equal, print −1−1.
Otherwise, in the first line print ?k — the minimum number of operations required to make the strings equal. In each of the next ?k lines print two integers — the index in the string ?s and the index in the string ?t that should be used in the corresponding swap operation.
Examples
input
4 abab aabb
output
2 3 3 3 2
input
Copy
1 a b
output
-1
input
8 babbaabb abababaa
output
3 2 6 1 3 7 8
解题思路:
比如下图这种情况,最佳的交换方式是一定的。所以只需要在第一个串中统计s[i]!=t[i]且s[i]='a'的位置,计数cnt1,每两个为一组按照下图的交换方式交换。同理也需要统计s[i]!=t[i]且s[i]='b'的位置,计数cnt2,处理方法同上。
注意:如cnt1和cnt2都为奇数的,那么处理完后会剩下下图这种情况,处理方法如下:
,交换方法:==》==》
如果cnt1 /cnt2中只有一个为奇数的话,无解。
ac代码:
#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\n", cnt);
for(int i = 0; i+1 < a.size(); i += 2)
printf("%d %d\n", a[i], a[i+1]);
for(int i = 0; i+1 < b.size(); i += 2)
printf("%d %d\n", b[i], b[i+1]);
if((a.size()&1) && (b.size()&1))
{
printf("%d %d\n", a[a.size()-1], a[a.size()-1]);
printf("%d %d\n", a[a.size()-1], b[b.size()-1]);
}
}
}