HDU1181 变形课(搜索或并查集)

来源:互联网 发布:数据比对公式 编辑:程序博客网 时间:2024/06/03 20:31

   原题链接:点击打开链接

   这道题我分别用了搜索和并查集做了一次,题目不难,可以看成一个有向图。

   贴并查集代码:

#include <iostream>#include <string>using namespace std;string str;int father[30];find(int x){    if(x!=father[x])        father[x]=find(father[x]);    return father[x];}void mere(int x,int y){    x=find(x);    y=find(y);    if(x!=y)        father[y]=x;}int main(){    int i;    while(cin>>str)    {        memset(father,0,sizeof(father));        for(i=0;i<29;i++)            father[i]=i;        int len=str.length();        int x=find(str[0]-'a');        int y=find(str[len-1]-'a');        if(x!=y&&y!='b'-'a')            mere(x,y);        while(cin>>str)        {            if(!str.compare("0"))                break;            len=str.length();            x=find(str[0]-'a');            y=find(str[len-1]-'a');            if(x!=y&&y!='b'-'a')                mere(x,y);        }        x=find('m'-'a');        y=father['b'-'a'];        if(x!=y)            cout<<"No."<<endl;        else            cout<<"Yes."<<endl;    }    return 0;}


再贴上搜索的代码:

#include <iostream>#include <vector>#include <string.h>#include <string>#include <queue>using namespace std;vector<int>map[30];string str;int visit[30],flag;queue<int>q;void bfs(int s,char m){    int i;    visit[s]=1;    q.push(s);    while(!q.empty())    {        int e=q.front();        q.pop();        for(i=0;i<map[e].size();i++)        {            int sbsbsb=map[e][i];            if(map[e][i]==m-'a')            {                flag=1;                break;            }            if(map[e][i]&&!visit[map[e][i]])            {                q.push(map[e][i]);                visit[map[e][i]]=1;            }        }    }    while(!q.empty())        q.pop();    for(i=0;i<30;i++)        map[i].clear();}int main(){    while(cin>>str)    {        memset(visit,0,sizeof(visit));        int len=str.length();        flag=0;        map[str[0]-'a'].push_back(str[len-1]-'a');        while(cin>>str)        {            if(!str.compare("0"))                break;            len=str.length();            map[str[0]-'a'].push_back(str[len-1]-'a');        }        bfs('b'-'a','m');        if(!flag)            cout<<"No."<<endl;        else            cout<<"Yes."<<endl;    }    return 0;}


原创粉丝点击