Suantoujun was surrounded by the Dark Legion on an island, and all the roads leading to the Guard Legion had the Dark Legion in charge. Fortunately, there is a sealed gate created by the ancient gods on the island, which can lead to the guards. It is rumored that no one has been able to lift the seal.
There is a string of text on the door of the seal, containing only lowercase letters, with a kThere are k operation rules, each of which can transform one character into another character. After any number of operations, if you can finally transform the text on the sealed door into the text to unlock the sealed door, the sealed door will be opened.
Tuantoujun has super strong combat power, but he is not good at calculating. Please help Tuantoujun to calculate how many times he needs to operate at least to unlock the sealed door.
input format
Enter a string in the first line, the length is not more than 10001 0 0 0 , containing only lowercase letters, represents the text on the Sealed Gate.
Enter a string in the second line, containing only lowercase letters, and ensure that the length is equal to the first string, indicating the text that can unlock the sealed door.
Enter an integer k in the third line (0 \le k \le 676)k(0≤k≤676)。
next kk lines, each line outputs the character a separated by two spaces a, bb , indicating that one operation can change the character aa is converted to character bb。
output format
If Mr. Garantou can open the door of the seal, output the minimum number of operations. Otherwise output a line of -1−1。
Sample output
6
The meaning of the question is to give us the goal of going from one string to another string and then give a single route of certain characters
Find the sum of the shortest paths for each character conversion
analyze
You can use floyd to find the transitive closure. For the path a->b given in the figure, it means that e[a][b]=1 Run the shortest path with flody
The complexity is not high O (26*26*26)
Note that the two points of the path in the input data may be the same
#include<bits/stdc++.h> using namespace std; const int maxd = 1e7; int e [30] [30]; intmain() { ios::sync_with_stdio(0); string from,to; getline(cin,from); getline(cin,to); int k; cin>>k; while(k--){ char ss,ee; cin>>ss>>ee; if(ss==ee)continue; e[ss-'a'][ee-'a']=1; } for(int i=0;i<26;i++){ for(int j=0;j<26;j++) if(i!=j&&e[i][j]==0) e[i][j] = maxd; } for(int k=0;k<26;k++){ for(int i=0;i<26;i++){ for(int j=0;j<26;j++) if(e[i][j]>e[i][k]+e[k][j]) e[i][j] = e[i][k]+e[k][j]; } } int ans=0; for(int i=0;i<from.length();i++){ char a = from[i]; char b = to[i]; if(e[a-'a'][b-'a']!=maxd)ans+=e[a-'a'][b-'a']; else { years=-1; break; } } cout<<ans<<endl; return 0; }