AcWing 860. Evaluación de gráficos bipartitos por método de coloración (Java) _Gráfico bipartito_Método de coloración_DFS

Método de teñido para determinar el gráfico bipartito.

Enlace del título original

①. Título

Inserte la descripción de la imagen aquí

②. Pensando

Inserte la descripción de la imagen aquí

  • Anillo impar: un anillo formado por bordes impares.
  • Gráfico bipartito: si y solo si el gráfico no contiene anillos impares, no hay bordes dentro de los dos conjuntos
	//DFS
* 染色可以使用12区分不同颜色,用0表示未染色
* 遍历所有点,每次将未染色的点进行dfs, 默认染成1或者2
* 由于某个点染色成功不代表整个图就是二分图,因此只有某个点染色失败才能立刻break/return
*

③. Puntos de aprendizaje

二分图_染色法

④. Implementación del código

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main {
    
    
	/*
	 * 奇数环:由奇数条边形成的一个环
	 * 二分图 当且仅当图中不含奇数环,两个集合内部没有边
	 */
	//DFS
	/*
	 * 染色可以使用1和2区分不同颜色,用0表示未染色
	 * 遍历所有点,每次将未染色的点进行dfs, 默认染成1或者2
	 * 由于某个点染色成功不代表整个图就是二分图,因此只有某个点染色失败才能立刻break/return
	 */
	static int N=200010,n,m,idx;     
	static int[] e=new int[N],ne=new int[N],h=new int[N]; //邻接矩阵存储
	static int[] vi=new int[N];
	
	public static void main(String[] args) throws IOException {
    
    
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		String[] s = br.readLine().split(" ");
		n=Integer.parseInt(s[0]);
		m=Integer.parseInt(s[1]);
		Arrays.fill(h,-1);
		while(m-->0) {
    
    
			s=br.readLine().split(" ");
			int a=Integer.parseInt(s[0]);
			int b=Integer.parseInt(s[1]);
			add(a,b);//无向图 两条边都加入到邻接矩阵
			add(b,a);
		}
		
		boolean flag=true;
		for (int i =1; i <=n; i++) {
    
    
			if(vi[i]==0) {
    
    
				if(!dfs(i,1)) {
    
    
					//出现矛盾
					flag=false;
					break;
				}
			}
		}
		if(flag) {
    
    
			System.out.println("Yes");
		}else {
    
    
			System.out.println("No");
		}
	}
	 static void add(int a,int b) {
    
    
		 e[idx]=b;
		 ne[idx]=h[a];
		 h[a]=idx++;
	 }
	 
	 //dfs(u,c)表示把u号点染色成c颜色,并且判断从u号点开始染其他相连的点是否染成功
	 static boolean dfs(int i,int color) {
    
    
		 vi[i]=color;
		 //给当前节点的子节点全部染成一种颜色
		 for (int j=h[i];j!=-1;j=ne[j]) {
    
    
			int nextNode=e[j];
			if(vi[nextNode]==0) {
    
     //若下个节点为染色,dfs进行递归染不同颜色
				if(!dfs(nextNode,3-color)) {
    
     
					return false;
				}
			}else if(vi[nextNode]==color) {
    
     //若相邻节点颜色相同直接false
				return false;
			}
		}
		 return true;
	 }
	
}

Inserte la descripción de la imagen aquí

Supongo que te gusta

Origin blog.csdn.net/weixin_45480785/article/details/114155980
Recomendado
Clasificación