Codeforces Round #389 Div.2 B. Santa Claus and Keyboard Check
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.
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.
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.
helloworld
ehoolwlroz
3
h e
l o
d z
hastalavistababy
hastalavistababy
0
merrychristmas
christmasmerry
-1
开个link数组,判断字符与字符间的对应关系。
如果所有不同的字符对都满足双向对应,那么有解。
1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<cstring> 5 #include<queue> 6 using namespace std; 7 const int mxn=1010; 8 int read(){ 9 int x=0,f=1;char ch=getchar(); 10 while(ch<'0' || ch>'9'){if(ch=='-')f=-1;ch=getchar();} 11 while(ch>='0' && ch<='9'){x=x*10-'0'+ch;ch=getchar();} 12 return x*f; 13 } 14 char link[mxn]; 15 char s[mxn]; 16 char c[mxn]; 17 int k=0; 18 char ans1[mxn],ans2[mxn]; 19 bool vis[mxn]; 20 int main(){ 21 int i,j; 22 scanf("%s%s",s,c); 23 int len=strlen(s); 24 if(len!=strlen(c)){printf("-1\n");return 0;} 25 for(i=0;i<len;i++){ 26 if(c[i]!=link[s[i]]){ 27 if(!link[s[i]]){ 28 link[s[i]]=c[i]; 29 } 30 else{printf("-1\n");return 0;} 31 } 32 if(s[i]!=link[c[i]]){ 33 if(!link[c[i]]){ 34 link[c[i]]=s[i]; 35 } 36 else {printf("-1\n");return 0;} 37 } 38 } 39 for(i=0;i<26;i++){ 40 int tmp='a'+i; 41 if(!link[tmp])continue; 42 if(link[tmp]!=tmp && !vis[tmp]){ 43 ans1[++k]=tmp; 44 ans2[k]=link[tmp]; 45 vis[tmp]=vis[link[tmp]]=1; 46 } 47 } 48 printf("%d\n",k); 49 for(i=1;i<=k;i++){ 50 printf("%c %c\n",ans1[i],ans2[i]); 51 } 52 return 0; 53 }