-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDiscount on crackers.cpp
72 lines (68 loc) · 1.31 KB
/
Discount on crackers.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include<bits/stdc++.h>
#define ll long long
using namespace std;
const ll mod = 1e9 + 7;
bool dfs(vector<char> adj[],char a,char b,vector<bool>&vis){
queue<char> qt;
qt.push(a);
vis[a-'a'] = true;
while(!qt.empty()){
char a = qt.front();
qt.pop();
for(auto it:adj[a-'a']){
if(it==b)
return true;
else if(!vis[it-'a']){
vis[it-'a'] = true;
qt.push(it);
}
}
}
return false;
}
void solve(){
string s,t;
cin>>s;
cin>>t;
int m;
cin>>m;
vector<char> adj[26];
while(m--){
string k;
cin>>k;
char a = k[0];
char b = k[k.length()-1];
adj[a-'a'].push_back(b);
}
if(s.length()!=t.length()){
cout<<"NO\n";
return;
}
int ct = 0;
for(int i=0;i<s.length();i++){
if(s[i]==t[i]){
ct++;
continue;
}
else{
vector<bool> vis(26,false);
if(dfs(adj,s[i],t[i],vis))
ct++;
}
}
if(ct==s.length()){
cout<<"YES\n";
}
else
cout<<"NO\n";
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int t;
cin>>t;
while(t--){
solve();
}
return 0;
}