HDU1116(欧拉回路+并查集)

先用并查集来判断图是否连通,然后再根据欧拉回路的出度和入度的性质来判断是否为欧拉回路。

关键是建边,我们可以把字符串看成是一条边,首字母为出发点,尾字母为目的点,建边。

#include <stdio.h>
#include <string.h>
#include <string>
#include <iostream>
#include <algorithm>
#include <vector>
#include <math.h>
#include <map>
#include <queue>
#include <stack>
#include <set>
#define M 100000+5
#define LL long long
#define Ld __int64
#define eps 0.00001
#define INF 999999999
#define MOD 112233
#define MAX 26
#define PI acos(-1.0)
using namespace std;

int father[M];
int into[M],out[M];
set<int> s;

int find(int x)
{
    if(x!=father[x])
        father[x]=find(father[x]);
    return father[x];
}

void merge(int x,int y)
{
    int fx=find(x);
    int fy=find(y);
    if(fx!=fy)
        father[fx]=fy;
}

void init()
{
    for(int i=0;i<M;i++)
    {
        into[i]=0;
        out[i]=0;
        father[i]=i;
    }
    s.clear();
}

int main()
{
    int t;
    char ch[1005];
    scanf("%d",&t);
    while(t--)
    {
        int n;
        init();
        scanf("%d",&n);
        getchar();
        for(int i=1;i<=n;i++)
        {
            scanf("%s",ch);
            int a=ch[0]-'a'+1;
            int l=strlen(ch);
            int b=ch[l-1]-'a'+1;
            into[b]++;
            out[a]++;
            int x=find(a);
            int y=find(b);
            if(x!=y)
                merge(x,y);
            s.insert(a);
            s.insert(b);
        }
        int num=0;
        set<int>::iterator it;
        for(it=s.begin();it!=s.end();it++)
        {
            if(father[*it]==*it && (into[*it] || out[*it]))
                num++;
        }
        if(num!=1)
            printf("The door cannot be opened.\n");
        else
        {
            int f1=0,f2=0,f3=0;
            for(it=s.begin();it!=s.end();it++)
            {
                int p=*it;
                if((into[p]-out[p])==1)
                    f1++;
                if((out[p]-into[p])==1)
                    f2++;
                if(into[p]==out[p])
                    f3++;
            }
            if(f1==1 && f2==1 && (f1+f2+f3)==(s.size()))
                printf("Ordering is possible.\n");
            else if(f1==0 && f2==0 && f3==s.size())
                printf("Ordering is possible.\n");
            else
                printf("The door cannot be opened.\n");
        }
    }
    return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值