1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | #include <stdio.h> #include <vector> #include <queue> #include <utility> using namespace std; vector<vector<int> > diff; int team[105] = { 0 }; //-1, 1 두 팀으로 구분 void bfs(int idx) { queue<pair<int, int>> q; team[idx] = 1; q.push(make_pair(idx, 1)); while (!q.empty()) { int cur = q.front().first; int t = q.front().second; q.pop(); for (int i = 0; i < diff[cur].size(); i++) { int adv = diff[cur][i]; if (team[adv] != 0) continue; team[adv] = -t; q.push(make_pair(adv, -t)); } } } int main() { int t; scanf("%d", &t); diff.resize(t + 1); for (int i = 1; i <= t; i++) { int n; scanf("%d", &n); for (int j = 0; j < n; j++) { int tmp; scanf("%d", &tmp); diff[i].push_back(tmp); } } for (int i = 1; i <= t; i++) if (team[i] == 0) bfs(i); vector<int> red; vector<int> blue; for (int i = 1; i <= t; i++) { if (team[i] == 1) red.push_back(i); if (team[i] == -1) blue.push_back(i); } printf("%d\n", red.size()); for (int i = 0; i < red.size(); i++) printf("%d ", red[i]); printf("\n%d\n", blue.size()); for (int i = 0; i < blue.size(); i++) printf("%d ", blue[i]); } | cs |
레드블랙 트리를 연상시키는 풀이방식이었다
노드를 한칸씩 띄어서 갈때마다 다른 team 으로 배정한 다음에,
맨 마지막에 서로 같은 팀끼리 정리해주는 방식을 취했다.
발상이 조금 필요했으나, 할만한 문제였다
'알고리즘 > BFS' 카테고리의 다른 글
6593 상범 빌딩 (0) | 2020.03.12 |
---|---|
9205 맥주 마시면서 걸어가기 (0) | 2020.01.21 |
3184 양 (0) | 2020.01.20 |
2251 물통 (0) | 2020.01.20 |
12761 돌다리 (0) | 2020.01.20 |