首先来总结一下做欧拉回路,欧拉路径问题的对策
欧拉回路;所有边都经过且只经过一次,最后一个点回到起点
欧拉通路:所有边都经过且只经过一次,最后一个点任意不能是起点
判断欧拉回路的办法:
首先所有图要联通
无向图:每一个点的度都为偶数即可
有向图:每一个点的出度与入度即可
判断欧拉路径的方法:
无向图:有俩个点的度数为奇数,有从其中一个奇数顶点到另一个的奇数顶点
有向图:有俩个点各自的出度与入度分别相差一,从出度比入度小一的点开始到另一个点结束。
从算法上讨论欧拉路径(如果是欧拉回路就一定是路径)
1.无向图首先判断是否连通,其次判断看各点的度
2.有向图首先存图时将图按无向图考虑,看是否连通,其次判断各个点的出度和入度
// 单词.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
#include<vector>
#include<queue>
#include<string>
#include<cstring>
using namespace std;
const int maxn = 30;
int graph[maxn][maxn];
string w;
int in[maxn];
int out[maxn];
bool vis[maxn];
int from, to;
int n;
void dfs(int u)
{
vis[u] = 0;
for (int i = 1;i <= 26;i++)
{
if (graph[u][i]&&vis[i])
{
dfs(i);
}
}
}
void init()
{
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
memset(graph, 0, sizeof(graph));
memset(vis, false, sizeof(vis));
}
bool solve(int m)
{
int in1 = 0, out1 = 0;
for (int i = 0;i < m;i++)
{//有向图看成无向图判断连通关系
cin >> w;
from = w[0] - 'a' + 1;
to = w[w.length() - 1] - 'a' + 1;
graph[from][to]++, graph[to][from]++;
vis[from] = true;
vis[to] = true;
out[from]++;
in[to]++;
}
dfs(from);
for (int i = 1;i <= 26;i++)
{
if (vis[i])
{
return false;
}
if (in[i] != out[i])
{//从定义考虑是否有欧拉回路
if (in[i] - out[i] == 1)in1++;
else if (out[i] - in[i] == 1)out1++;
else
{
return false;
}
}
}
if ((in1 == 1 && out1 == 1) || (in1 == 0 && out1 == 0))
{
return true;
}
else
{
return false;
}
}
int main()
{
cin >> n;
while (n--)
{
init();
int m;
cin >> m;
if (solve(m))
{
cout << "Ordering is possible." << endl;
}
else
{
cout << "The door cannot be opened." << endl;
}
}
}
这是判断无向图的题目
```cpp
#include <iostream>
#include<cstring>
#include<vector>
using namespace std;
int degree[130];
int father[130];
int graph[130][130];
char a[2];
char ans[1330];int n;
int find(int x)
{
if (father[x] != x)
{
father[x] = find(father[x]);
}
return father[x];
}
void dfs(int x)
{
for (int i = 64;i <= 125;i++)
{
if (graph[x][i])
{
graph[x][i] = graph[i][x] = 0;
dfs(i);
}
}
ans[n--] = x;
}
int main()
{
cin >> n;
for (int i = 64;i <= 125;i++)
{
father[i] = i;
}
for (int i = 0;i < n;i++)
{
cin >> a;
graph[a[0]][a[1]] = graph[a[1]][a[0]] = 1;
degree[a[0]]++;
degree[a[1]]++;
int xx = find(a[0]);
int yy = find(a[1]);
father[xx] = yy;
}
int number = 0;
for (int i = 64;i <= 125;i++)
{
if (father[i] == i && degree[i])number++;
}
if (number != 1) {
cout << "No Solution" << endl;return 0;
}
int head = 0;
int cnt = 0;
for (int i = 64;i <= 125;i++)
{
if (degree[i] & 1)
{
if(head==0)head = i;
cnt++;
}
}
if (cnt&&cnt != 2) { cout << "No Solution" << endl;return 0; }
if (head == 0)
{
for (int i = 64;i <= 125;i++)
{
if (degree[i])
{
head = i;
break;
}
}
}
dfs(head);
cout << ans;
}