uva 10129 并查集的运用

#include<bits/stdc++.h>
using namespace std;
const int maxm=30;
int pre[maxm],son,far,in[maxm],out[maxm];
int ffind(int x)
{
    return pre[x]==x?x:pre[x]=ffind(pre[x]);
}
void unite(int x,int y)
{
    x=ffind(x);
    y=ffind(y);
    if(x!=y)
        pre[x]=y;
}
int main()
{
    string str;
    int kase;
    cin>>kase;
    while(kase--)
    {
        int n,cnt=0,n_in=0,n_out=0;
        cin>>n;
        memset(in,0,sizeof(in));
        memset(out,0,sizeof(out));
        for(int i=0;i<maxm;i++)
            pre[i]=i;
        for(int i=0; i<n; i++)
        {
            cin>>str;
            far=str[0]-'a';
            son=str[str.size()-1]-'a';
            out[far]++;
            in[son]++;
            unite(son,far);
        }
        for(int i=0; i<27; i++)
        {
            if(pre[i]==i&&(in[i]||out[i]))
                cnt++;
            if(in[i]!=out[i])
            {
                if(in[i]==out[i]+1)
                    n_in++;
                else if(in[i]+1==out[i])
                    n_out++;
                else n_in+=maxm;
            }
        }
        if(cnt!=1||!((n_in==1&&n_out==1)||(n_in==0&&n_out==0)))
            cout<<"The door cannot be opened."<<endl;
        else cout<<"Ordering is possible."<<endl;
    }
    return 0;
}

你可能感兴趣的:(uva 10129 并查集的运用)