zoukankan      html  css  js  c++  java
  • goj 变形课(并查集)

    Problem Description:

    呃......变形课上Harry碰到了一点小麻烦,因为他并不像Hermione那样能够记住所有的咒语而随意的将一个棒球变成刺猬什么的,但是他发现了变形咒语的一个统一规律:如果咒语是以a开头b结尾的一个单词,那么它的作用就恰好是使A物体变成B物体. 
    Harry已经将他所会的所有咒语都列成了一个表,他想让你帮忙计算一下他是否能完成老师的作业,将一个B(ball)变成一个M(Mouse),你知道,如果他自己不能完成的话,他就只好向Hermione请教,并且被迫听一大堆好好学习的道理.
    

    Input:

    测试数据有多组。每组有多行,每行一个单词,仅包括小写字母,是Harry所会的所有咒语.数字0表示一组输入结束.

    Output:

    如果Harry可以完成他的作业,就输出"Yes.",否则就输出"No."(不要忽略了句号)

    Sample Input:

    so
    soon
    river
    goes
    them
    got
    moon
    begin
    big
    0
    big
    keep
    dim
    0

    Sample Output:

    Yes.
    No.
    解题思路:并查集的应用!只需将每个字符串首尾的关系链接成一棵树,最后判断'b'的祖先是否为'm'即可。
    AC代码:
     1 #include<bits/stdc++.h>
     2 using namespace std;
     3 const int maxn=26;
     4 int fa[maxn];string word;
     5 void init(){for(int i=0;i<maxn;++i)fa[i]=i;}
     6 int findt(int x){
     7     while(fa[x]!=x)x=fa[x];
     8     return x;
     9 }
    10 void unite(int x,int y){
    11     x=findt(x),y=findt(y);
    12     if(x!=y)fa[x]=y;
    13 }
    14 int main(){
    15     while(cin>>word){
    16         init();
    17         unite(word[0]-'a',word[word.length()-1]-'a');
    18         while(cin>>word&&word!="0")
    19             unite(word[0]-'a',word[word.length()-1]-'a');
    20         if(findt('b'-'a')=='m'-'a')cout<<"Yes."<<endl;//判断'b'的祖先是否为'm'
    21         else cout<<"No."<<endl;
    22     }
    23     return 0;
    24 }
  • 相关阅读:
    This counter can increment, decrement or skip ahead by an arbitrary amount
    LUT4/MUXF5/MUXF6 logic : Multiplexer 8:1
    synthesisable VHDL for a fixed ratio frequency divider
    Bucket Brigade FIFO SRL16E ( VHDL )
    srl16e fifo verilog
    DualPort Block RAM with Two Write Ports and Bytewide Write Enable in ReadFirst Mode
    Parametrilayze based on SRL16 shift register FIFO
    stm32 spi sdcard fatfs
    SPI bus master for System09 (2)
    SQLSERVER中的自旋锁
  • 原文地址:https://www.cnblogs.com/acgoto/p/9251668.html
Copyright © 2011-2022 走看看