C. Swap Letters 01字符串最少交换几次相等
C. Swap Letters
Monocarp has got two strings ss and tt having equal length. Both strings consist of lowercase Latin letters "a" and "b".
Monocarp wants to make these two strings ss and tt equal to each other. He can do the following operation any number of times: choose an index pos1pos1 in the string ss, choose an index pos2pos2 in the string tt, and swap spos1spos1 with tpos2tpos2.
You have to determine the minimum number of operations Monocarp has to perform to make ss and tt equal, and print any optimal sequence of operations — or say that it is impossible to make these strings equal.
The first line contains one integer nn (1≤n≤2⋅105)(1≤n≤2⋅105) — the length of ss and tt.
The second line contains one string ss consisting of nn characters "a" and "b".
The third line contains one string tt consisting of nn characters "a" and "b".
If it is impossible to make these strings equal, print −1−1.
Otherwise, in the first line print kk — the minimum number of operations required to make the strings equal. In each of the next kk lines print two integers — the index in the string ss and the index in the string tt that should be used in the corresponding swap operation.
4 abab aabb
2 3 3 3 2
1 a b
-1
8 babbaabb abababaa
3 2 6 1 3 7 8
In the first example two operations are enough. For example, you can swap the third letter in ss with the third letter in tt. Then s=s= "abbb", t=t= "aaab". Then swap the third letter in ss and the second letter in tt. Then both ss and tt are equal to "abab".
In the second example it's impossible to make two strings equal.
题意:给你两个字符串,问最少需要交换多少次可以使这两个字符串相等,并且输出交换方案
题解:因为字符只有a,b两种;所以不相等的时候只有两种情况
1、
a
b
2、
b
a
分别统计这两种情况的出现次数,用k1,k2表示
如果k1,k2有一个为奇数,一个为偶数 ,即(k1+k2)%2==1,则不可能交换之后两字符串相等,输出 -1
否则 先让同一种不相等情况的先两两交换,交换次数为k1/2+k2/2
最后判断k1,k2是否都是奇数,如果是的话,最后只剩下如下一组不相等的情况
a b
b a
这里需要交换两次才能使两字符串相等
------------1
b b
a a
------------2
b a
b a
------------
#include<iostream> #include<algorithm> #include<cstring> #include<math.h> #include<stack> #include<string.h> #include<string> #include<vector> #define ll long long using namespace std; int pos1[200005],pos2[200005]; int main() { string s1,s2; int t; cin>>t; cin>>s1; cin>>s2; int k1=0,k2=0; for(int i=0;i<t;i++) { if(s1[i]!=s2[i]&&s1[i]=='a') pos1[k1++]=i+1;//输出下标是从1开始 if(s1[i]!=s2[i]&&s1[i]=='b') pos2[k2++]=i+1; } if((k1+k2)%2==1)//k1,k2一个为奇数,一个为偶数 cout<<-1<<endl; else { int cnt=k1/2+k2/2; if(k1%2==1&&k2%2==1)//如果k1,k2为奇数最后交换的时候要交换两次 cnt=cnt+2; cout<<cnt<<endl; int i,j; for(i=0;i+1<k1;i=i+2) cout<<pos1[i]<<' '<<pos1[i+1]<<endl; for(j=0;j+1<k2;j=j+2) cout<<pos2[j]<<' '<<pos2[j+1]<<endl; if(i!=k1&&j!=k2)//处理最后一次交换下标 { cout<<pos1[k1-1]<<' '<<pos1[k1-1]<<endl; cout<<pos1[k1-1]<<' '<<pos2[k2-1]<<endl; } } return 0; }