There are two lengths of only lowercase letters to n strings S . 1 , S 2 , and m groups of letters corresponding relationship, the relationship between each group of two-letter c . 1 and c 2 , representing c . 1 can directly into c 2 , you need to determine S . 1 whether by this m is converted to a group relationship S 2 .
Input Format
A first line of input n- ( . 1 ≤ n- ≤ 100 ) , representative length of the string.
The second and third rows two input strings S . 1 , S 2 .
A fourth line input m ( . 1 ≤ m ≤ 325 ) , there are representative of m groups relationship.
Subsequently m -th row, the i row two characters U i , V i , the representative U i can be directly changed to V i .
Output Format
If S . 1 by the m conversion relationship becomes set S 2 , output "YES", and otherwise outputs "NO".
Sample
6 aabbcc cdbcad 4 a c c a a d b c
YES
prompt
Can be converted many times, such can be converted to a b, and b may be converted is c, then a can be converted to c.
Sample a: aabbcc-> cabbcc-> cdbbcc-> cdbccc- > cdbcac-> cdbcaa-> cdbcad
Thinking: determining character by character, each character is judged whether s1 s2 corresponding character can be achieved
#include<iostream> #include<string> #include<vector> #include<queue> #include<cstring> using namespace std; int n; string s1,s2; int mark[500]; char tt; int flag=0; vector<char>ve[500]; void bfs(char x){ queue<char >que; que.push(x); int c=int (x); mark[c]=1; while(que.size()){ char y=que.front(); que.pop(); if(y==tt){ flag=1; break; } char yy; int yyy; for(int i=0;i<ve[y].size();i++){ yy=ve[y][i]; yyy=int(yy); if(mark[yyy]==0&&yy!=y){ mark[yyy]=1; que.push(yyy); } } } } int main(){ cin>>n; cin>>s1>>s2; int t; cin>>t; char a,b; for(int i=0;i<t;i++){ cin>>a>>b; ve[a].push_back(b);//表示a可以变成b } for(int i=0;i<n;i++) { if(s1[i]==s2[i]) continue ; else { tt=s2[i]; memset(mark,0,sizeof(mark)); flag=0; bfs(s1[i]); if(flag==0) break; } } if(flag==0) puts("NO"); else puts("YES"); return 0; }