-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy path1686 Building Teams.cpp
108 lines (90 loc) · 2.1 KB
/
1686 Building Teams.cpp
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
// JAI BAJARANG BALI
// manitianajay45
// give me some sunshine, give me some rain ,give me another chance to grow up once again....
// sab moh maya hai....
/*
test case for "impossible":
3 3
1 2
1 3
2 3
basically using level order traversal technique using bfs if on the odd level we will give 1 to all the elements and on even level we will give 2
or we can use it using dfs simply maintaining a fucntion
dfs(node,flag);
where flag will be reverse after each iteration
color=flag?1:2;
*/
#include <bits/stdc++.h>
using namespace std;
#define ll int
ll n, m;
vector<ll> graph[100005];
vector<bool> visited(100005, false);
int main()
{
cin >> n >> m;
vector<pair<ll,ll>> edges;
for (ll i = 0; i < m; i++)
{
ll u, v;
cin >> u >> v;
graph[u].push_back(v);
graph[v].push_back(u);
edges.push_back({u,v});
}
queue<ll> q;
vector<ll> ans(n + 1, 1);
for (ll i = 1; i <= n; i++)
{
if (!visited[i])
{
while (!q.empty())
{
q.pop();
}
q.push(i);
q.push(-1);
ll an = 0;
while (q.size() > 1)
{
ll u = q.front();
q.pop();
if (u == -1)
{
an++;
q.push(-1);
continue;
}
if (an % 2 == 1)
{
ans[u] = 2;
}
visited[u] = true;
for (auto i : graph[u])
{
if (!visited[i])
{
q.push(i);
visited[i] = true;
}
}
}
}
}
bool flag=false;
for(ll i=0;i<m;i++){
if(ans[edges[i].first]==ans[edges[i].second]){
flag=true;
break;
}
}
if(flag){
cout<<"IMPOSSIBLE"<<endl;
return 0;
}
for(ll i=1;i<=n;i++){
cout<<ans[i]<<" ";
}
cout<<endl;
return 0;
}