杭电1878_欧拉回路——java

Problem Description
欧拉回路是指不令笔离开纸面,可画过图中每条边仅一次,且可以回到起点的一条回路。现给定一个图,问是否存在欧拉回路?
 

Input
测试输入包含若干测试用例。每个测试用例的第1行给出两个正整数,分别是节点数N ( 1 < N < 1000 )和边数M;随后的M行对应M条边,每行给出一对正整数,分别是该条边直接连通的两个节点的编号(节点从1到N编号)。当N为0时输入结
束。
 

Output
每个测试用例的输出占一行,若欧拉回路存在则输出1,否则输出0。
 

Sample Input
 
 
3 3
1 2
1 3
2 3
3 2
1 2
2 3
0
 

Sample Output
 
 
1
0

    欧拉回路的两个充要条件,只要满足就行:

1、是一个连通图,不存在独立的岛,这个可以通过并查集去实现,将图连接后,并查集查找set数组,记录是否只有一个根节点,如果是,则代表已经构成连通图。

2、每个节点的度是偶数。只要用个二维数组存储节点与节点的关系,就可以统计每个节点的度。

import java.util.*;

public class Main {
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNextInt()){
            int N = sc.nextInt();
            if(N == 0)
                break;
            int M = sc .nextInt();
            int[] set = new int[N+1];
            for(int i = 1;i <= N; i++){
                set[i] = i;
            }
            int[][] flag = new int[N+1][N+1];
            int[] count = new int[N+1];
            for(int i = 0; i < M;i++){
                int e1 = sc.nextInt();
                int e2 = sc.nextInt();
                flag[e1][e2] = 1;
                flag[e2][e1] = 1;
                count[e1]++;
                count[e2]++;
                join(set,e1,e2);
            }
            //第一个充要条件,连通
            int lt = 0;
            for(int i = 1; i <= N;i++){
                if(set[i] == i)
                    lt++;
            }
            if(lt != 1){
                System.out.println(0);
                continue;
            }
            //第二个充要条件,每个点的度都是偶数
            boolean judge = true;
            for(int i = 1;i <= N;i++){
                if((count[i]&1) == 1){
                    judge = false;
                    break;
                }
            }
            if(judge){
                System.out.println(1);
            }
            else
                System.out.println(0);
        }
    }
    public static int find(int[] set,int data){
        int res = data;
        while(set[res] != res){
            res = set[res];
        }
        //路径压缩
        while(data != res){
            int temp = set[data];
            set[data] = res;
            data = temp;
        }
        return res;
    }

    public static void join(int[] set ,int a,int b){
        int x = find(set,a);
        int y = find(set,b);
        if(x < y){
            set[y] = x;
        }
        else{
            set[x] = y;
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值