PAT (Advanced Level) 1126. Eulerian Path (25) 解题报告

来源:互联网 发布:linux多线程机制 编辑:程序博客网 时间:2024/06/03 20:43

1126. Eulerian Path (25)

时间限制
300 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

In graph theory, an Eulerian path is a path in a graph which visits every edge exactly once. Similarly, an Eulerian circuit is an Eulerian path which starts and ends on the same vertex. They were first discussed by Leonhard Euler while solving the famous Seven Bridges of Konigsberg problem in 1736. It has been proven that connected graphs with all vertices of even degree have an Eulerian circuit, and such graphs are called Eulerian. If there are exactly two vertices of odd degree, all Eulerian paths start at one of them and end at the other. A graph that has an Eulerian path but not an Eulerian circuit is called semi-Eulerian. (Cited from https://en.wikipedia.org/wiki/Eulerian_path)

Given an undirected graph, you are supposed to tell if it is Eulerian, semi-Eulerian, or non-Eulerian.

Input Specification:

Each input file contains one test case. Each case starts with a line containing 2 numbers N (<= 500), and M, which are the total number of vertices, and the number of edges, respectively. Then M lines follow, each describes an edge by giving the two ends of the edge (the vertices are numbered from 1 to N).

Output Specification:

For each test case, first print in a line the degrees of the vertices in ascending order of their indices. Then in the next line print your conclusion about the graph -- either "Eulerian", "Semi-Eulerian", or "Non-Eulerian". Note that all the numbers in the first line must be separated by exactly 1 space, and there must be no extra space at the beginning or the end of the line.

Sample Input 1:
7 125 71 21 32 32 43 45 27 66 34 56 45 6
Sample Output 1:
2 4 4 4 4 4 2Eulerian
Sample Input 2:
6 101 21 32 32 43 45 26 34 56 45 6
Sample Output 2:
2 4 4 4 3 3Semi-Eulerian
Sample Input 3:
5 81 22 55 44 11 33 23 45 3
Sample Output 3:
3 3 4 3 3Non-Eulerian

思路:判断欧拉图,半欧拉图,先并查集看联通,在看度数,全为偶数则为欧拉图,奇数度数有且仅有两个为半欧拉图

代码:

#include <cstdio>#include <vector>#include <iostream>#include <algorithm>#include <cmath>#include <queue>using namespace std;int f[505], degree[505];int find(int x){    return f[x] == x ? x : f[x] = find(f[x]);}void merge(int x, int y){    x = find(x);    y = find(y);    if(x != y) f[x] = y;}int main(){    int n, m, x, y;    for(int i = 0; i < 505; i++) f[i] = i;    scanf("%d%d", &n, &m);    for(int i = 0; i < m; i++)    {        scanf("%d%d", &x, &y);        merge(x, y);        degree[x] ++;        degree[y] ++;    }    printf("%d", degree[1]);    for(int i = 2; i <= n; i++)        printf(" %d", degree[i]);    printf("\n");    int sum = 0, gs = 0;    for(int i = 1; i <= n; i++)    {        if(f[i] == i) sum ++;        if(degree[i] % 2) gs ++;    }    if(sum == 1 && gs == 0) printf("Eulerian\n");    else if(sum == 1 && gs == 2) printf("Semi-Eulerian\n");    else printf("Non-Eulerian\n");    return 0;}



0 0
原创粉丝点击