Método de teñido para determinar el gráfico bipartito.
Enlace del título original
①. Título
②. Pensando
- 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
* 染色可以使用1和2区分不同颜色,用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 {
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++;
}
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) {
if(!dfs(nextNode,3-color)) {
return false;
}
}else if(vi[nextNode]==color) {
return false;
}
}
return true;
}
}