天天看點

UVA Play on Words

UVA Play on Words

    題意:按照一個單詞的最後一個字母和另一個字母的第一個字母就可以相連,是否可以實作把所有的單詞按照這種方式連接配接起來(第一個單詞的首字母可以不與最後一個單詞的最後一個字相同)能實作輸出Ordering...,不能實作輸出The ......

#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<queue>

int map[101][101];
int v[101];
int n;
int a[100],b[100];

int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        char s[1010];
        memset(a,0,sizeof(a));
        memset(b,0,sizeof(b));
        memset(v,0,sizeof(v));
        memset(map,0,sizeof(map));
        scanf("%d",&n);
        for(int i=0; i<n; i++)
        {
            memset(s,0,sizeof(s));
            scanf("%s",s);
            int len = strlen(s);
            int x = s[0] - 'a';
            int y = s[len-1] - 'a';
            map[x][y] = 1;
            a[x]++;
            b[y]++;
            v[y] = 1;
        }
        int psum = 0;
        int qsum = 0;
        int sum1 = 0;
        for(int i=0; i<26; i++)
        {
            sum1 += v[i];
            int c = a[i] - b[i];
            if(c<0)
            {
                qsum += (-c);
            }
            else
            {
                psum += c;
            }
        }
        for(int i=0; i<26; i++)
        {
            for(int j=0; j<26; j++)
            {
                for(int k=0; k<26; k++)
                {
                    if(map[j][i] == 1 && map[i][k] == 1)
                    {
                        map[j][k] = 1;
                    }
                }
            }
        }
        int flag = 0;
        for(int i=0; i<26; i++)
        {
            int count = 0;
            for(int j=0; j<26; j++)
            {
                if(map[i][j] == 1 && v[j] == 1)
                {
                    count++;
                }
            }
            //printf("sum1 = %d     count = %d\n",sum1,count);
            if(sum1 == count)
            {
                flag = 1;
                //printf("i = %d\n",i);
                break;
            }
        }
        if((psum == 1 && qsum == 1) || (psum == 0 && qsum == 0))
        {
            if(flag == 1)
            {
                printf("Ordering is possible.\n");
            }
            else
            {
                printf("The door cannot be opened.\n");
            }
        }
        else
        {
            printf("The door cannot be opened.\n");
        }
    }
    return 0;
}