이분 그래프

BiBi·2021년 2월 6일
0

코딩테스트연습

목록 보기
59/66
#include <iostream>
#include <queue>
#include <stdio.h>

std::vector<int> graph[20001];
int visited[20001];
int k, v, e;

void bfs(int v) {
	std::queue<int> q;
	q.push(v);
	visited[v] = 1;
	while (!q.empty()) {
		int x = q.front();
		q.pop();
		for (int i = 0;i < graph[x].size();i++) {
			if (visited[x] == 1) {
				if (visited[graph[x][i]] == 0) {
					q.push(graph[x][i]);
					visited[graph[x][i]] = 2;
				}
			}
			else if (visited[x] == 2) {
				if (visited[graph[x][i]] == 0) {
					q.push(graph[x][i]);
					visited[graph[x][i]] = 1;
				}
			}
		}
	}
}

bool isBinary() {
	for (int i = 1;i <= v;i++) {
		for (int j = 0;j < graph[i].size();j++) {
			if (visited[i] == visited[graph[i][j]]) {
				return false;
			}
		}
	}
	return true;
}

int main() {
	scanf("%d", &k);

	for (int i = 0;i < k;i++) {
		scanf("%d %d", &v, &e);

		for (int j = 1;j <= v;j++) {
			graph[j].clear();
			visited[j] = 0;
		}

		for (int j = 1;j <= e;j++) {
			int a, b;
			scanf("%d %d", &a, &b);
			graph[b].push_back(a);
			graph[a].push_back(b);
		}
		for (int j = 1;j <= v;j++) {
			if (visited[j] == 0) {
				bfs(j);
			}
		}
		if (isBinary()) {
			printf("YES\n");
		}
		else {
			printf("NO\n");
		}
	}
}
profile
Server Network Engineer

0개의 댓글