-
Notifications
You must be signed in to change notification settings - Fork 35
Description
🎯 Problem Information
- Problem Name: Building Teams
- CSES Link: https://cses.fi/problemset/task/1668
- Category: Graphs
- Estimated Difficulty: Medium
💡 Proposed Approach
Describe the algorithm/approach you plan to use:
-
The problem can be solved using Graph Coloring (Bipartite Check).
-
Each student is represented as a node, and each friendship as an undirected edge.
-
We must divide pupils into two teams such that no two friends are in the same team.
-
This can be checked using BFS or DFS traversal with two colors:
- Assign color
1to a node. - Assign color
2to all its neighbors. - If any adjacent nodes have the same color → print
"IMPOSSIBLE".
- Assign color
-
If traversal finishes successfully for all components, print the color of each node.
-
Time Complexity: O(N + M)
-
Space Complexity: O(N + M)
📝 Implementation Notes
Any special considerations or optimizations needed:
- Requires fast I/O
- Needs modular arithmetic
- Large input constraints
- Edge cases to consider:
- Smallest input (n = 1)
- Disconnected graphs
- Odd cycles (no valid bipartite division)
- Large inputs (n = 10^5, m = 2×10^5)
🏷️ Labels
Please add appropriate labels:
-
hacktoberfest -
good first issue -
help wanted
👤 Assignee
- I would like to work on this issue
- I'm available for guidance/review
📎 Additional Context
This code implements a Graph Coloring approach using BFS traversal to check bipartiteness.
If a valid two-coloring is possible, the nodes are divided into two teams (1 and 2).
If any conflict arises (same color on both ends of an edge), the answer is "IMPOSSIBLE".
🧠 Code Implementation
#include <bits/stdc++.h>
using namespace std;
/*
========================================
Author: Vinayak Goel
May the WA avoid you
========================================
*/
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m;
cin >> n >> m;
vector<vector<int>> adj(n + 1);
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
vector<int> color(n + 1, 0);
for (int i = 1; i <= n; ++i) {
if (color[i] != 0) continue;
queue<int> q;
q.push(i);
color[i] = 1;
while (!q.empty()) {
int u = q.front();
q.pop();
for (int v : adj[u]) {
if (color[v] == 0) {
color[v] = 3 - color[u];
q.push(v);
} else if (color[v] == color[u]) {
cout << "IMPOSSIBLE\n";
return 0;
}
}
}
}
for (int i = 1; i <= n; ++i)
cout << color[i] << " ";
cout << "\n";
return 0;
}