poj 1386 欧拉图的应用

本文介绍了一种通过重新排列磁盘上的单词,使每个单词首字母与前一个单词尾字母相同的算法实现。利用有向图和欧拉路径理论,通过构建特定的数据结构来判断是否能完成这种排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:有一些磁盘排成一行 , 每个磁盘上有一个单词,问这些磁盘能不能通过重新排列 , 使得每个单词的第一个字母和前一个单词的最后一个字母想通?

解法:本题中 , 对于每一个单词来说只有前后两个字母才是有用的 , 而每个单词可以看做是从首字母到尾字母的一条有向边 , 然后通过输入 , 我们就能构成一个有向图 , 因此我们只需要判断这个有向图是否存在欧拉回路或通路 。

注意:由于这个有向图可能不是一个弱连通图(基图不是一个连通图) , 因此我们要先判断是不是弱连通图

代码:


#include
#include
#include
using namespace std;

int rudu[30] , chudu[30] , p[30];
int n , pre[30];
char xy[1010];

void init()
{
    for(int i = 0; i < 26; i++)
        p[i] = i;
    memset(rudu , 0 , sizeof(rudu));
    memset(pre , 0 , sizeof(pre));
    memset(chudu , 0 , sizeof(chudu));
}

int find(int x)
{
    int g = x , h;
    while(p[x] != x)  x = p[x];

    while(p[g] != x)
    {
        h = p[g];
        p[g] = x;
        g = h;
    }

    return x;
}

int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        init();
        scanf("%d" , &n);
        int i , j , x , y , z;
        int g , h;
        for(i = 1; i <= n; i++)
        {
            scanf("%s" , xy);
            z = strlen(xy);
            x = xy[0]-97 , y = xy[z-1]-97;
            pre[x] = pre[y] = 1;
            chudu[x] += 1 , rudu[y] += 1;
            g = find(x) , h = find(y);
            p[g] = h;
        }

        x = y = g = h = 0;

        for(i = 0; i < 26; i++)
            if(pre[i] && p[i] == i)  x += 1;

        if(x > 1) {cout<<"The door cannot be opened."<<endl; continue;}
   
        x = 0;
        for(i = 0; i < 26; i++)
        {
            if(rudu[i]-chudu[i] == 1)  x += 1;
            else if(rudu[i]-chudu[i] == -1)  y += 1;
            else if(rudu[i] != chudu[i])  g += 1;
        }

        if(x+y+g == 0)  cout<<"Ordering is possible."<<endl;
        else if(x == 1 && y == 1 && g == 0)  cout<<"Ordering is possible."<<endl;
        else cout<<"The door cannot be opened."<<endl;

    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值