Personal Practice - PAT Level A - 1126 Eulerian Path

Topic link https://pintia.cn/problem-sets/994805342720868352/problems/994805349851185152

Topic: Graph theory. Tell you

  1. Euler circuit: all points have an even degree
  2. Euler path: there are only two points with an odd degree

Given the edge information of an undirected graph, output the degree of all nodes, and find out whether the graph is an Euler circuit or an Euler path or neither.

To calculate the degree of a node, count the number of points whose degree is an odd number. Note that the point tested by test point 3 is whether the graph is connected. If the graph is not connected (that is, there are multiple connected components), then it is definitely not satisfied. Therefore, at the beginning, DFS is used to count the number of points of the first connected component. If it is less than the number of connected components, Nthere are multiple connected components.

void DFS(int id) {
    
    
    known[id] = true;
    cnt++;
    for (int i = 0; i < adj[id].size(); i++) {
    
    
        if (!known[adj[id][i]])
            DFS(adj[id][i]);
    }
}

full code

#include <iostream>
#include <cstdio>
#include <cmath>
#include <vector>
#include <algorithm>
#include <queue>
#include <map>
#include <set>


using namespace std;


int N, M;
vector<int> adj[501];
vector<int> degree;
vector<bool> known;
int odd;
int cnt;


void DFS(int id) {
    
    
    known[id] = true;
    cnt++;
    for (int i = 0; i < adj[id].size(); i++) {
    
    
        if (!known[adj[id][i]])
            DFS(adj[id][i]);
    }
}


int Judge() {
    
    
    if (cnt < N)
        return 0;

    for (int v = 1; v <= N; v++) {
    
    
        if (degree[v] % 2)
            odd++;
    }

    if (odd == 2)
        return 1;
    else if (odd == 0)
        return 2;
    else
        return 0;
}



int main() {
    
    
    scanf("%d %d", &N, &M);
    degree.resize(N+1, 0);
    known.resize(N+1, false);
    for (int i = 0; i < M; i++) {
    
    
        int v1, v2;
        scanf("%d %d", &v1, &v2);
        adj[v1].push_back(v2);
        adj[v2].push_back(v1);
        degree[v1]++;
        degree[v2]++;
    }

    printf("%d", degree[1]);
    for (int i = 2; i <= N; i++)
        printf(" %d", degree[i]);
    printf("\n");

    DFS(1);

    switch (Judge()) {
    
    
        case 0 : printf("Non-Eulerian"); break;
        case 1: printf("Semi-Eulerian"); break;
        default: printf("Eulerian");
    }

    return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324143443&siteId=291194637