例题6-16 UVa10129-Play On Word(欧拉道路)

把每个单词的首位两个字母看做一条边的两个顶点,这样就可以把图建起来了。之后先深搜看看这个图是不是连通图,不是的话不存在欧拉道路。之后判断每个顶点的出度入度是否相同,如果不相同的点超过两个,也不存在欧拉道路。如果所有点的出度入度都相同,或者不相同的两个点恰好可以作为起点和终点,则存在欧拉道路。我是用邻接表实现的。

题目链接:UVa 10129

AC代码:

#include 
#include 
#include 
using namespace std;

list<int> notEqual;
int cnt;

class Graph {
	set<int> vex;  //顶点集
	list<int>* adj;  //邻接表
	int* indegree, * outdegree;  //入度出度
	bool* visit;  //访问标志
public:
	Graph();
	~Graph();
	void addEdge(int v, int w);
	bool is_euler(), dfs(int v);   //深搜判断是否为连通图,如果不是连通图,不可能排成首尾相同的序列
	int start();  //找到入度为0的点作为深搜的起点,如果没有就从任意点开始
};
Graph::Graph() {
	adj = new list<int>[27];
	visit = new bool[27];
	indegree = new int[27];
	outdegree = new int[27];
	for (int i = 0; i < 27; i++) {
		visit[i] = false;
		indegree[i] = outdegree[i] = 0;
	}
}
Graph::~Graph() {
	delete[] adj;
	delete[] indegree;
	delete[] outdegree;
}
void Graph::addEdge(int v, int w) {
	adj[v].push_back(w);
	outdegree[v]++, indegree[w]++;
	vex.insert(v), vex.insert(w);
}
bool Graph::is_euler() {
	for (auto& p : vex)
		if (indegree[p] != outdegree[p]) {
			notEqual.push_back(p);
		}
	if (notEqual.size() > 2) return false;  //出度入度不相等的点大于2个,不可能存在欧拉道路
	if (notEqual.empty()) return true;  //所有点的出度入度都相等,存在欧拉道路
	int n1 = notEqual.front(); notEqual.pop_front();
	int n2 = notEqual.front();
	if (indegree[n1] - outdegree[n1] == 1 && outdegree[n2] - indegree[n2] == 1 || indegree[n2] - outdegree[n2] == 1 && outdegree[n1] - indegree[n1] == 1)  //出入度关系判断
		return true;
	return false;
}
bool Graph::dfs(int v) {
	if (visit[v]) return false;
	visit[v] = true;
	cnt++;
	for (auto& p : adj[v])
		if (!visit[p])
			dfs(p);
	if (cnt != vex.size())
		return false;
	return true;
}
int Graph::start() {
	for (auto& p : vex)
		if (indegree[p] == 0)
			return p;
	return -1;
}
int main() {
	int T, n, start;
	string str;
	cin >> T;
	while (T--) {
		cin >> n;
		Graph G;
		cnt = 0;
		while (n--) {
			cin >> str;
			G.addEdge(str[0] - 'a', str[str.length() - 1] - 'a');
		}
		if (G.start() >= 0)
			start = G.start();
		else
			start = str[0] - 'a';
		if (!G.dfs(start)) {
			cout << "The door cannot be opened." << endl;
			continue;
		}
		notEqual.clear();
		if (G.is_euler())
			cout << "Ordering is possible." << endl;
		else
			cout << "The door cannot be opened." << endl;
	}
	return 0;
}

你可能感兴趣的:(第6章,数据结构基础)