每日一九度之 题目1027:欧拉回路

时间限制:1 秒

内存限制:32 兆

特殊判题:

提交:3352

解决:1693

题目描述:
    欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
输入:
    测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结束。
输出:
    每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。
样例输入:
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
样例输出:
1
0

我似乎写过类似的题解,但是忘了是哪个了,在写一次吧,哈哈!

欧拉回路的特点:

1、连通图

2、节点数全为偶数

 

这题还可以用DFS做,可以试着去做下,但是我自己感觉还是并查集好写一点,主要是代码少!

//Asimple
#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cctype>
#include <cstdlib>
#include <stack>
#include <cmath>
#include <string>
#include <queue>
#define INF 100000
using namespace std;
const int maxn = 1005;
typedef long long ll;
int fa[maxn], deg[maxn];
int n, m, x, y;
//节点度数全部为偶数的连通图 
int find_set(int x){
    if( fa[x] == x ) return x;
    else return fa[x] = find_set(fa[x]);
}

void make_set(int x, int y){
    x = find_set(x);
    y = find_set(y);
    if( x != y ){
        fa[x] = y;
    }
}

int main(){
    while( scanf("%d",&n) && n ){
        bool f = true;
        int cnt = 0;
        for(int i=1; i<=n; i++){
            fa[i] = i;
            deg[i] = 0;
        }
        scanf("%d",&m);
        while( m -- ){
            scanf("%d %d",&x,&y);
            make_set(x,y);
            ++deg[x];
            ++deg[y];
        }
        for(int i=1; i<=n; i++){
            //是否是连通图 
            if( fa[i] == i ){
                cnt ++ ;
                if( cnt > 1 ){
                    f = false ;
                    break;
                }
            }
            //节点数全为偶
            if( deg[i] & 1 ){
                f = false;
                break;
            } 
        }
        if( f ) printf("1\n");
        else printf("0\n");
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/Asimple/p/5846365.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值