UVA - 10129 Play on Words

/*
  把字母看作结点,单词看成有向边,则,问题有解,当且仅当图中有欧拉路径
  
  存在欧拉道路的条件,见小白书 P169
  
  判断连通的方法有两种: 1. DFS 2. 并查集
*/


#include <iostream>
#include <vector>
#include <string>
#include <cstring>
using namespace std;

const int N = 256;

int used[N]; // 是否出现过
int deg[N]; // 度数 

int pa[N];
int find ( int x )
{
	return pa[x] != x ? pa[x] = find (pa[x]) : x;
}

void init() //初始化数组,初始化并查集 
{
	memset( used, 0, sizeof(used) );
	memset( deg, 0, sizeof(deg) );
	
	for (int ch = 'a'; ch <= 'z'; ch++)
	pa[ch] = ch;
}

int main()
{
	int t;
	cin >> t;
	
	while (t--)
	{
		int n;
		string word;
		
		cin >> n;
		init();
		int cc = 26; // 连通块个数
		
		for (int i = 0; i < n; i++)
		{
			cin >> word;
			char c1 = word[0], c2 = word[ (int)word.size() - 1];
			deg[c1]++;
			deg[c2]--;
			used[c1] = used[c2] = 1;
			int s1 = find(c1), s2 = find(c2);
			if (s1 != s2)
			{
				pa[s1] = s2;
				cc--;
			}
		}
		
		vector<int> v;
		for (int ch = 'a'; ch <= 'z'; ch++)
		{
			if (!used[ch]) cc--; //没出现过的字母
			else if (deg[ch] != 0) v.push_back(deg[ch]); 
		}
		
		bool ok = false;
		if ( cc == 1 && ( v.empty() || ( v.size() == 2 && ( v[0] == 1 || v[0] == -1) ) ) ) ok = true;
		
		if (ok) cout << "Ordering is possible.";
		else cout << "The door cannot be opened.";
		cout << endl;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值