码迷,mamicode.com
首页 > 其他好文 > 详细

poj1386有向图判断是否存在欧拉回路或者欧拉路

时间:2017-10-12 23:01:40      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:out   har   string   欧拉   bsp   题意   字符串   mes   存在   

 

技术分享

 

 

 

 有向图的图联通是指基图联通,也就是把有向图的边改成无向图然后看是否连通。判断联通可用dfs或者并查集。

 

题意就是给你n个由小写字母构成的字符串,问你能不能将这n个字符串连接起来,B能接在A后面的条件是A的最后一个字母==B的第一个字母。

 

然后就是将26个小写字母看成顶点集,对于一个字符串,其首字母向尾字母连一条单向边构图。

 

#include<cstdio>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=35;
int in[N],out[N],ans;
char s[N*100];
vector<int>G[N];
bool vis[N];
void dfs(int u)
{
    for(int i=0; i<(int)G[u].size(); ++i)
    {
        if(vis[G[u][i]])
        {
            ++ans;
            vis[G[u][i]]=0;
            dfs(G[u][i]);
        }
    }
}
int main()
{
    int T,n;
    for(scanf("%d",&T); T--;)
    {
        scanf("%d",&n);
        memset(vis,0,sizeof(vis));
        memset(in,0,sizeof(in));
        memset(out,0,sizeof(out));
        for(int i=0; i<35; ++i) G[i].clear();
        int cont=ans=0;
        while(n--)
        {
            scanf("%s",s);
            int st=s[0],ed=s[strlen(s)-1];
            st-=a,ed-=a;
            G[st].push_back(ed);
            G[ed].push_back(st);
            ++in[ed];
            ++out[st];
            if(!vis[st]) ++cont;vis[st]=1;
            if(!vis[ed]) ++cont;vis[ed]=1;
        }
        for(n=0; n<35; ++n) if(!G[n].empty()) break;
        vis[n]=0,++ans;
        dfs(n);
        if(ans!=cont)
        {
            puts("The door cannot be opened.");
            continue;
        }
        bool ok=1,k1=0,k2=0;
        for(int i=0; i<26; ++i)
        {
            if(in[i]==out[i]) continue;
            else if(in[i]-out[i]==1&&!k1) k1=1;
            else if(out[i]-in[i]==1&&!k2) k2=1;
            else
            {
                ok=0;
                break;
            }
        }
        if(ok) puts("Ordering is possible.");
        else puts("The door cannot be opened.");
    }
}

 

poj1386有向图判断是否存在欧拉回路或者欧拉路

标签:out   har   string   欧拉   bsp   题意   字符串   mes   存在   

原文地址:http://www.cnblogs.com/mfys/p/7658431.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!