Same String
单点时限: 2.0 sec
内存限制: 512 MB
有两个只由小写字母组成的长度为n的字符串s1,s2和m组字母对应关系,每一组关系由两个字母c1和c2组成,代表c1可以直接变成c2,你需要判断s1是否可以通过这m组关系转换为s2。
输入格式
第一行输入一个n(1≤n≤100),代表字符串的长度。
第二行和第三行输入两个字符串s1,s2。
第四行输入一个m(1≤m≤325),代表有m组关系。
接下来m行,第i行两个字符ui,vi,代表ui可以直接变为vi。
输出格式
如果s1可以通过这些m组关系转化变为s2,输出”YES”,否则输出”NO”。
样例
input
6
aabbcc
cdbcad
4
a c
c a
a d
b c
output
YES
提示
可以转换多次,比如a可以转换为b,而b可以转换为c,则a可以转换为c。
样例一:aabbcc->cabbcc->cdbbcc->cdbccc->cdbcac->cdbcaa->cdbcad
用bfs模板一遍过了,但是比赛结束后学长讲题的时候讲传递闭包才更简单,(上个学期水过去的离散有讲)
先贴bfs代码,等复(yu)习懂了传递闭包再来贴简单的代码
#include<iostream>
#include<algorithm>
#include<queue>
#include<string.h>
using namespace std;
struct word{
char from,to;
};
int num;
word ww[1000];
int head[1000];
int vis[26];
string s1,s2;
int n,m,flag;
char w1,w2;
void bfs(char x,char y){
memset(vis,0,sizeof(vis));
queue<char> que;
vis[x-'a']=1;
que.push(x);
flag=0;
while(!que.empty()){
char nn;
nn=que.front();
que.pop();
if(nn==y){
flag=1;
break;
}
for(int i=0;i<n;i++){
if(ww[i].from ==nn&&!vis[ww[i].to -'a']){//cout<<"from:"<<ww[i].from<<" to:"<<ww[i].to<<endl;
que.push(ww[i].to );
vis[ww[i].to -'a']=1;
}
}
}
}
int main(){
cin>>m;
cin>>s1;
cin>>s2;
cin>>n;
num=0;
memset(head,-1,sizeof(head));
for(int i=0;i<n;i++){
cin>>ww[i].from >>ww[i].to ;
}
int ans=0;
for(int i=0;i<m;i++){
bfs(s1[i],s2[i]);
if(!flag){
ans=1;
// cout<<"i:"<<i<<endl;
}
}
if(ans) cout<<"NO"<<endl;
else cout<<"YES"<<endl;
return 0;
}
/*
6
aabbcc
cdbcad
4
a c
c a
a d
b c
*/