版权声明:我的GitHub:https://github.com/617076674。真诚求星! https://blog.csdn.net/qq_41231926/article/details/84888693
我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set
原题链接:https://pintia.cn/problem-sets/15/problems/859
题目描述:
知识点:图的深度优先遍历、欧拉回路
思路:和PAT-ADVANCED1126——Eulerian Path同样的解法
解题之前需要提前知道欧拉回路的判断条件:
如果无向图连通并且所有节点的度数都是偶数,则回路存在;否则不存在。
C++代码:
#include<iostream>
#include<vector>
using namespace std;
struct node{
int v;
};
int N, M;
vector<int> graph[1001];
bool visited[1001];
int degree[1001];
void dfs(int nowVisit);
int main(){
std::ios::sync_with_stdio(false);
cin >> N >> M;
fill(degree + 1, degree + N + 1, 0);
for(int i = 0; i < M; i++){
int v1, v2;
cin >> v1 >> v2;
graph[v1].push_back(v2);
graph[v2].push_back(v1);
degree[v1]++;
degree[v2]++;
}
int blocks = 0;
for(int i = 1; i <= N; i++){
if(!visited[i]){
dfs(i);
blocks++;
}
}
if(blocks != 1){ //如果不是一个连通图
printf("0\n");
return 0;
}
for(int i = 1; i <= N; i++){
if(degree[i] % 2 != 0){
printf("0\n");
return 0;
}
}
printf("1\n");
return 0;
}
void dfs(int nowVisit){
visited[nowVisit] = true;
for(int i = 0; i < graph[nowVisit].size(); i++){
int u = graph[nowVisit][i];
if(!visited[u]){
dfs(u);
}
}
}
C++解题报告: