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

LRJ-Example-06-16-Uva10129

时间:2018-01-21 01:06:11      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:mes   namespace   log   ann   each   for   letters   mem   pos   

#include <cstdio>
#include <cstring>
#include <vector>

using namespace std;

const int maxn = 1000 + 5; // at most 1000 lowercase characters

// union find set, each set is a tree
// only letters ‘a‘ through ‘z‘ will appear, so totally 26 nodes
const int maxc = 26;

int parent[maxc]; // parent of each node

// find the root node of the set of node x
int findSet(int x) {
    return parent[x] == x ? x : findSet(parent[x]);
}

int used[maxc];
int degree[maxc]; // degree = out degree - in degree

int main() {
    int T; 
    int N; // 1 <= N <= 100000
    char word[maxn]; 

    scanf("%d", &T);
    while(T--) {
        scanf("%d", &N);
        
        memset(used, 0, sizeof(used));
        memset(degree, 0, sizeof(degree));

        // init the sets
        for(int i = 0; i < maxc; i++) parent[i] = i;
        int numSet = maxc;

        for(int i = 0; i < N; i++) {

            // read each word
            scanf("%s", word);
            int first = word[0] - a;
            int last = word[strlen(word) - 1] - a;
            // there is an edge first --> last
            degree[first]++;// out degree 
            degree[last]--;// in degree

            used[first] = used[last] = 1;

            int setFirst = findSet(first);
            int setLast = findSet(last);

            if(setFirst != setLast) {
                // union
                parent[setFirst] = setLast;
                numSet--;
            }
        }
            
        vector<int> d;
        for(int i = 0; i < maxc; i++) {
            if(!used[i]) 
                numSet--;
                else if (degree[i] != 0) 
                    d.push_back(degree[i]);
            }

            bool ok = false;
            if(numSet == 1 && // all nodes are connected
                    // Euler circuit, all nodes have degree 0
                   (d.empty() || 
                    // Euler path, if d[0] == 1, then d[1] == -1, and vice versa
                   (d.size() == 2 && (d[0] == 1 || d[0] == -1)))) 
                ok = true;

            if(ok) printf("Ordering is possible.\n");
            else printf("The door cannot be opened.\n");
    }

    return 0;
}
    

 

LRJ-Example-06-16-Uva10129

标签:mes   namespace   log   ann   each   for   letters   mem   pos   

原文地址:https://www.cnblogs.com/patrickzhou/p/8322386.html

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