uva 10129

主要是求能否形成联通的欧拉回路

并查集+ 欧拉回路判断

一开始用dfs判断联通,死活A不出来,Wa了好多次………哭……

并查集一次就AC了

感觉还是并查集代码好写一点,

因为dfs还要判断入口在哪里……2333333

判断欧拉回路:

1.判断联通(dfs|并查集)

2.判断欧拉回路的条件(1.要么所有的点出度等于入度,2.要么只能有一个出度比入度大于1(入口),一个入度比出度小于1(出口)其他的点必须出度等于入度)

代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <stack>
#include <cctype>
#include <string>
#include <malloc.h>
#include <queue>
#include <map>

using namespace std;
const int INF = 0xffffff;
const double Pi = 4 * atan(1);
const int Maxn = 200 + 10;
//int dir2[8][2] = {{-1,0},{0,-1},{-1,1},{1,-1},{-1,-1},{1,0},{0,1},{1,1}};

int in[26];
int out[26];
int f[26];

int _f(int i){
    if(f[i] == i)
        return i;
    return _f(f[i]);
}

int main()
{
#ifndef ONLINE_JUDGE
    freopen("inpt.txt","r",stdin);
#endif
    int t;
    cin >> t;
    int n;
    while(t--){
        cin >> n;
        memset(in,0,sizeof(in));
        memset(out,0,sizeof(out));
        for(int i = 0;i < 26;i++)
            f[i] = i;
        while(n--){
            char str[1100];
            cin >> str;
            int len = strlen(str);
            in[ str[0] - 'a' ]++;
            out[ str[len-1] - 'a' ]++;
            int x = _f( str[0] - 'a' );
            int y = _f( str[len-1] - 'a');
            if(x != y)
                f[x] = y;
        }
        int cnt = 0;
        int start = 0;
        int enn = 0;
        for(int i = 0;i < 26;i++){
            if(in[i] != out[i]){
                cnt++;
                if(in[i] - out[i] == 1)
                    start++;
                else if(out[i] - in[i] == 1)
                    enn++;
                else
                    cnt = 3;
                if(cnt > 2)
                    break;
            }
        }
        bool flag = 1;
        if(start == 1 && enn == 1 && cnt == 2){
            flag = 0;
        }
        else if(cnt == 0){
            flag = 0;
        }
        if(!flag){
            for(int i = 0;i < 26;i++){
                if(in[i] || out[i]){
                    for(int j = 0;j < 26;j++){
                        if( (in[j] || out[j] ) && _f(i) != _f(j)){
                            flag = 1;
                            break;
                        }
                    }
                    break;
                }
            }
        }
        if(flag)
            cout << "The door cannot be opened." << endl;
        else
            cout << "Ordering is possible." << endl;
    }
    return 0;
}
View Code

 

posted @ 2015-01-17 09:39  寒饼干  阅读(252)  评论(0编辑  收藏  举报