Skip to content

Commit d798ce3

Browse files
authored
Merge pull request #121 from vingoel26/feature/building_teams
Solution for Building Teams
2 parents 6bab4be + 38d5af9 commit d798ce3

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
/*
2+
CSES - Building Teams
3+
Link: https://cses.fi/problemset/task/1668
4+
Difficulty: Medium
5+
Time Complexity: O(N + M)
6+
Space Complexity: O(N + M)
7+
8+
Approach:
9+
Use graph coloring (bipartite check) with BFS to assign pupils to two teams.
10+
Each pupil is a node and each friendship is an undirected edge. We attempt to color
11+
the graph with two colors (1 and 2) so that no adjacent nodes share the same color.
12+
Process every connected component (graph may be disconnected).
13+
14+
Key Insights:
15+
- A graph is bipartite iff it is 2-colorable (no odd-length cycles).
16+
- BFS is used to color level-by-level: if current node has color c, all uncolored
17+
neighbors get color 3 - c.
18+
- If an edge connects two nodes with the same color, the graph is not bipartite,
19+
and the answer is "IMPOSSIBLE".
20+
- Iterative BFS avoids recursion depth issues on large inputs.
21+
*/
22+
23+
#include <bits/stdc++.h>
24+
using namespace std;
25+
26+
int main() {
27+
ios::sync_with_stdio(false);
28+
cin.tie(nullptr);
29+
30+
// Read number of pupils (n) and friendships (m)
31+
int n, m;
32+
cin >> n >> m;
33+
34+
// Build adjacency list for 1-indexed nodes
35+
vector<vector<int>> adj(n + 1);
36+
for (int i = 0; i < m; ++i) {
37+
int a, b;
38+
cin >> a >> b;
39+
// undirected friendship edge
40+
adj[a].push_back(b);
41+
adj[b].push_back(a);
42+
}
43+
44+
// color[i] = 0 -> unvisited, 1 or 2 -> team assignment
45+
vector<int> color(n + 1, 0);
46+
47+
// Process all components to handle disconnected graphs
48+
for (int start = 1; start <= n; ++start) {
49+
// If already colored in previous BFS, skip
50+
if (color[start] != 0) continue;
51+
52+
// Start BFS from this unvisited node, assign color 1
53+
queue<int> q;
54+
color[start] = 1;
55+
q.push(start);
56+
57+
// Standard BFS loop
58+
while (!q.empty()) {
59+
int u = q.front();
60+
q.pop();
61+
62+
// Check all neighbors of u
63+
for (int v : adj[u]) {
64+
if (color[v] == 0) {
65+
// Assign the opposite color to the neighbor
66+
color[v] = 3 - color[u]; // 1 -> 2, 2 -> 1
67+
q.push(v);
68+
} else if (color[v] == color[u]) {
69+
// Conflict detected: same color on both ends of an edge
70+
cout << "IMPOSSIBLE\n";
71+
return 0;
72+
}
73+
}
74+
}
75+
}
76+
77+
// If we reach here, graph is bipartite; print team assignments
78+
for (int i = 1; i <= n; ++i) {
79+
if (i > 1) cout << ' ';
80+
cout << color[i];
81+
}
82+
cout << '\n';
83+
return 0;
84+
}

0 commit comments

Comments
 (0)