哥尼斯堡是位于普累格河上的一座城市,它包含两个岛屿及链接它们的七座桥,以下图所示。ios
能否走过这样的七座桥,并且每桥只走过一次?瑞士数学家欧拉(Leonhard Euler,1707—1783)最终解决了这个问题,并由此创立了拓扑学。测试
这个问题现在能够描述为判断欧拉回路是否存在的问题。欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且能够回到起点的一条回路。现给定一个无向图,问是否存在欧拉回路?spa
输入格式:
输入第一行给出两个正整数,分别是节点数NN (1\le N\le 10001≤N≤1000)和边数MM;随后的MM行对应MM条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到NN编号)。code
输出格式:
若欧拉回路存在则输出1,不然输出0。htm
输入样例1:
6 10 1 2 2 3 3 1 4 5 5 6 6 4 1 4 1 6 3 4 3 6
输出样例1:
1
输入样例2:
5 8 1 2 1 3 2 3 2 4 2 5 5 3 5 4 3 4
输出样例2:
0
第一次我蚍蜉撼树采用了DFS深度搜索的方式解决,果真最后两个测试点超时,下面 是我第一次尝试的代码:
#include<iostream> #include<vector> #define MAX 1000 using namespace std; int g[MAX][MAX]; int from; int been[MAX][MAX]; int cnt = 1; void clear(int n) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) been[i][j] = 0; } bool DFS(int fr, int n, int m) { //int been[MAX][MAX]; for (int j = 1; j <= n; j++) { if (j != fr && been[fr][j] == 0 && g[fr][j] == 1) { //cout<<"fr :"<<fr<<" to "<<j<<endl; //cout<<"cnt is "<<cnt<<endl; if (j == from) { if (cnt == m) return true; //cout<<"减啦"<<endl; //cnt--; continue; } cnt++; been[fr][j] = been[j][fr] = 1; if (cnt == m) return true; return DFS(j, n, m); } } return false; } int main() { int n, m, a, b; cin >> n >> m; int temp = m; while (temp--) { cin >> a >> b; g[a][b] = g[b][a] = 1; } for (int i = 1; i <= n; i++) { clear(n); cnt = 1; from = i; if (DFS(i, n, m)) { cout << 1; return 0; } } cout << 0; return 0; }
在网上搜索得知这是有关欧拉回路的知识:blog
欧拉回路:图G,若存在一条路,通过G中每条边有且仅有一次,称这条路为欧拉路,若是存在一条回路通过G每条边有且仅有一次,ci
称这条回路为欧拉回路。具备欧拉回路的图成为欧拉图。数学
判断欧拉路是否存在的方法string
有向图:图连通,有一个顶点出度大入度1,有一个顶点入度大出度1,其他都是出度=入度。
无向图:图连通,只有两个顶点是奇数度,其他都是偶数度的。
判断欧拉回路是否存在的方法
有向图:图连通,全部的顶点出度=入度。
无向图:图连通,全部顶点都是偶数度。
程序实现通常是以下过程:
1.利用并查集判断图是否连通,即判断p[i] < 0的个数,若是大于1,说明不连通。
2.根据出度入度个数,判断是否知足要求。
3.利用dfs输出路径。
正确代码
#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<sstream> #include<algorithm> #include<queue> #include<vector> #include<cmath> #include<map> #include<stack> #include<set> #include<fstream> #include<memory> #include<list> #include<string> using namespace std; typedef long long LL; typedef unsigned long long ULL; #define MAXN 1003 #define LLL 1000000000 #define INF 1000000009 /* DFS能搜到全部的点 */ vector<int> E[MAXN]; int pre[MAXN],n,m; int find(int x) { if (pre[x] == -1) return x; else return pre[x] = find(pre[x]); } void mix(int x, int y) { int fx = find(x), fy = find(y); if (fx != fy) { pre[fy] = fx; } } int main() { memset(pre, -1, sizeof(pre)); scanf("%d%d", &n, &m); int f, t; for (int i = 1; i <= n; i++) E[i].clear(); while (m--) { scanf("%d%d", &f, &t); mix(f, t); E[f].push_back(t); E[t].push_back(f); } int cnt = 0, num = 0; for (int i = 1; i <= n; i++) { if (E[i].size() % 2) cnt++; if (find(i) == i) num++; } if (cnt == 0 && num == 1) printf("1\n"); else printf("0\n"); return 0; }