B. Santa Claus and Keyboard Check
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
Santa Claus decided to disassemble his keyboard to clean it. After he returned all the keys back, he suddenly realized that some pairs of keys took each other’s place! That is, Santa suspects that each key is either on its place, or on the place of another key, which is located exactly where the first key should be.
In order to make sure that he’s right and restore the correct order of keys, Santa typed his favorite patter looking only to his keyboard.
You are given the Santa’s favorite patter and the string he actually typed. Determine which pairs of keys could be mixed. Each key must occur in pairs at most once.
Input
The input consists of only two strings s and t denoting the favorite Santa’s patter and the resulting string. s and t are not empty and have the same length, which is at most 1000. Both strings consist only of lowercase English letters.
Output
If Santa is wrong, and there is no way to divide some of keys into pairs and swap keys in each pair so that the keyboard will be fixed, print «-1» (without quotes).
Otherwise, the first line of output should contain the only integer k (k ≥ 0) — the number of pairs of keys that should be swapped. The following k lines should contain two space-separated letters each, denoting the keys which should be swapped. All printed letters must be distinct.
If there are several possible answers, print any of them. You are free to choose the order of the pairs and the order of keys in a pair.
Each letter must occur at most once. Santa considers the keyboard to be fixed if he can print his favorite patter without mistakes.
Examples
Input
helloworld
ehoolwlroz
Output
3
h e
l o
d z
Input
hastalavistababy
hastalavistababy
Output
0
Input
merrychristmas
christmasmerry
Output
-1
题意 : 圣诞老人决定拆开他的键盘来清洗它,当他把所有的键都拿回来后,他突然意识到有机个键放在彼此的位置上~即给出两串字符串,能否通过一些字符的替换使其中一串字符串可以转换成另一串字符串~
AC代码:
#include<bits/stdc++.h>
using namespace std;
const int K = 4e3 + 10;
char s1[K],s2[K];
int ma[K],bo[K];
int main()
{
scanf("%s %s",s1,s2);
int n = strlen(s1),cut = 0,i;
for(i = 0 ; i < n; i++){
if(!(!(ma[s1[i]] || ma[s2[i]]) || (ma[s1[i]] == s2[i] && ma[s2[i]] == s1[i]))) break;
else if(!ma[s1[i]]){
ma[s1[i]] = s2[i];
ma[s2[i]] = s1[i];
if(s1[i] != s2[i]) cut++; // 一样时无需替换
}
}
if(i < n) printf("-1\n");
else{
printf("%d\n",cut);
for(i = 0 ; i < n ;i++){
if(ma[s1[i]] != s1[i] && !bo[s1[i]] && !bo[ma[s1[i]]]){
printf("%c %c\n",s1[i],(char)ma[s1[i]]);
bo[s1[i]] = 1; // 避免重复输出
}
}
}
return 0;
}