AcWing 860. 染色法判定二分图--(Javascript) --bfs
原题链接
简单
作者:
cp777
,
2021-03-03 15:06:14
,
所有人可见
,
阅读 275
const N = 100010;
let head = new Array(N).fill(-1);
let edge = [];
let next = [];
let idx = 0;
let add = (a, b) => {
edge[idx] = b;
next[idx] = head[a];
head[a] = idx++;
}
let queue = [];
let color = new Int32Array(N);
let bfs = point => { //每一次bfs都会给一个连通块染色
queue.push([point, 1]); //每次起点染色1,不会冲突,因为每一次从头染色的部分与之前染过色的是不连通的
color[point] = 1;
while (queue.length) {
let top = queue.shift();
let p = top[0],
c = top[1];
for (let i = head[p]; i !== -1; i = next[i]) { //遍历所有相邻点
let j = edge[i];
if (!color[j]) { //相邻点未涂色
color[j] = 3 - c;
queue.push([j, 3 - c]);
} else if (color[j] === c) return false; //相邻点涂色了
}
}
return true;
}
let buf = '';
process.stdin.on('readable', function () {
let chunk = process.stdin.read();
if (chunk) buf += chunk.toString();
});
let getInputNums = line => line.split(' ').filter(s => s !== '').map(x => parseInt(x));
let getInputStr = line => line.split(' ').filter(s => s !== '');
process.stdin.on('end', function () {
buf.split('\n').forEach(function (line, lineIdx) {
if (lineIdx === 0) {
n = getInputNums(line)[0];
m = getInputNums(line)[1];
} else if (lineIdx <= m) {
let arr = getInputNums(line);
let a = arr[0];
let b = arr[1];
add(a, b);
add(b, a);
if (lineIdx === m) {
let flag = true;
for (let i = 1; i <= n; i++) { //防止图不连通
if (!color[i]) {
if (!bfs(i)) {
flag = false;
break;
}
}
}
if (flag) console.log('Yes');
else console.log('No');
}
}
});
});