hdu 1116 Play on Words

给n个单词,判断n个单词能否形成欧拉通路

要先判连通!

#include <iostream>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
int book[30], in[30];
int main()
{
	int t;
	scanf("%d", &t);
	while (t--)
	{
		queue<int>q;
		vector<int>v[30];
		memset(in, 0, sizeof in);
		memset(book, 0, sizeof book);
		int n;
		int all = 0, maxn = 0;
		char s[1005];
		scanf("%d", &n);
		while (n--)
		{
			scanf("%s", s);
			in[s[0] - 'a']++;
			in[s[strlen(s) - 1] - 'a']--;

			//vector和book用来判连通
			v[s[0] - 'a'].push_back(s[strlen(s) - 1] - 'a');
			v[s[strlen(s) - 1] - 'a'].push_back(s[0] - 'a');
			
			book[s[0] - 'a'] = 1;
			book[s[strlen(s) - 1] - 'a'] = 1;
		}
		//判连通
		for (int i = 0; i < 30; i++)
		{
			if (book[i])
			{
				q.push(i);
				book[i] = 0;
				break;
			}
		}
		while (!q.empty())
		{
			int temp = q.front();
			q.pop();
			for (auto it = v[temp].begin(); it != v[temp].end(); it++)
			{
				if (book[*it])
				{
					book[*it] = 0;
					q.push(*it);
				}
			}
		}
		//不连通
		for (int i = 0; i < 26; i++)
		{
			if (book[i])
			{
				puts("The door cannot be opened.");
				goto qwe;
			}
		}
		//若入度和出度有大于1或者小于-1,则不连通
		for (int i = 0; i < 26; i++)
		{
			if (in[i] > 1 || in[i] < -1)
			{
				puts("The door cannot be opened.");
				goto qwe;
			}
			all += in[i];
			if (in[i] == 1)
				maxn++;
		}
		//总入度和为0,最多只能有一个结点的入度为1,一个结点的出度为-1
		if (all == 0 && maxn <= 1)
			puts("Ordering is possible.");
		else
			puts("The door cannot be opened.");
	qwe:;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值