Skip to content

Commit 49eeee5

Browse files
committed
Graph
1 parent c06de13 commit 49eeee5

10 files changed

Lines changed: 722 additions & 3 deletions

File tree

Lines changed: 242 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,242 @@
1+
# https://maang.in/problems/Easy-Graph-Queries-400?resourceUrl=cs214-cp873-pl3337-rs400&returnUrl=%5B%22%2Fcourses%2FGraph-Level-1-214%3Ftab%3Dchapters%22%5D
2+
3+
"""
4+
Description
5+
You are given an undirected graph G with N nodes and M edges. You have to answer Q queries. Each query is one of the following two types.
6+
7+
Type 1: 1 X — print the size of the connected component containing node
8+
Type 2: 2 X Y — print YES if nodes X and Y are in the same connected component, otherwise print NO.
9+
10+
Input Format
11+
The first line contains three space-separated integers
12+
N, M, Q
13+
The next M lines each contain two integers u, v denoting an undirected edge between nodes u and v.
14+
15+
Each of the next Q lines contains a single query in one of the formats: 1X 2 X Y
16+
17+
Output Format
18+
Print
19+
Q lines as the answers to the
20+
Q
21+
Q queries, each on a new line.
22+
Constraints
23+
1≤N,M,Q≤105
24+
25+
Sample Input 1
26+
6 5 5
27+
1 2
28+
2 3
29+
1 3
30+
4 4
31+
5 6
32+
1 2
33+
1 4
34+
2 3 4
35+
1 5
36+
2 5 6
37+
Sample Output 1
38+
3
39+
1
40+
NO
41+
2
42+
YES
43+
"""
44+
45+
import sys
46+
from collections import defaultdict
47+
48+
input = sys.stdin.readline
49+
print = sys.stdout.write
50+
sys.setrecursionlimit(1 << 25)
51+
52+
MOD = 10**9 + 7
53+
INF = 10**18
54+
55+
56+
def read():
57+
return sys.stdin.buffer.read()
58+
59+
60+
def ints():
61+
return map(int, input().split())
62+
63+
64+
def list_ints():
65+
return list(map(int, input().split()))
66+
67+
68+
def write_line(value=""):
69+
sys.stdout.write(str(value) + "\n")
70+
71+
72+
def write_lines(values):
73+
sys.stdout.write("\n".join(map(str, values)))
74+
if values:
75+
sys.stdout.write("\n")
76+
77+
78+
def solve():
79+
[n, m, q] = list_ints()
80+
adj_list = defaultdict(list)
81+
for i in range(m):
82+
[u, v] = list_ints()
83+
if u != v:
84+
adj_list[u].append(v)
85+
adj_list[v].append(u)
86+
87+
comp_id = [-1] * (n + 1)
88+
cid = 0
89+
comp_size = []
90+
91+
for node in range(1, n + 1):
92+
if comp_id[node] == -1:
93+
size = 0
94+
stack = [node]
95+
comp_id[node] = cid
96+
97+
while stack:
98+
child = stack.pop()
99+
size += 1
100+
for nei in adj_list[child]:
101+
if comp_id[nei] == -1:
102+
comp_id[nei] = cid
103+
stack.append(nei)
104+
cid += 1
105+
comp_size.append(size)
106+
107+
for _ in range(q):
108+
query_list = list_ints()
109+
if len(query_list) == 2:
110+
write_line(comp_size[comp_id[query_list[1]]])
111+
else:
112+
if comp_id[query_list[1]] == comp_id[query_list[2]]:
113+
write_line("YES")
114+
else:
115+
write_line("NO")
116+
117+
118+
if __name__ == "__main__":
119+
solve()
120+
121+
"""
122+
No recursive DFS because of the stack overflow risk
123+
✅ Time Complexity
124+
Build graph: O(N + M)
125+
DFS traversal (all nodes): O(N + M)
126+
Each query:
127+
Type 1 (size): O(1)
128+
Type 2 (connected?): O(1)
129+
130+
👉 Total:
131+
132+
O(N+M+Q)
133+
✅ Space Complexity
134+
Adjacency list: O(N + M)
135+
Component array (comp_id): O(N)
136+
Component sizes: O(N) (worst case)
137+
138+
👉 Total:
139+
140+
O(N+M)
141+
"""
142+
143+
144+
import sys
145+
from collections import defaultdict
146+
147+
input = sys.stdin.readline
148+
print = sys.stdout.write
149+
sys.setrecursionlimit(1 << 25)
150+
151+
MOD = 10**9 + 7
152+
INF = 10**18
153+
154+
155+
def read():
156+
return sys.stdin.buffer.read()
157+
158+
159+
def ints():
160+
return map(int, input().split())
161+
162+
163+
def list_ints():
164+
return list(map(int, input().split()))
165+
166+
167+
def write_line(value=""):
168+
sys.stdout.write(str(value) + "\n")
169+
170+
171+
def write_lines(values):
172+
sys.stdout.write("\n".join(map(str, values)))
173+
if values:
174+
sys.stdout.write("\n")
175+
176+
177+
class DSU:
178+
def __init__(self, n):
179+
self.parent = list(range(n + 1))
180+
self.size = [1] * (n + 1)
181+
182+
def find(self, x):
183+
while self.parent[x] != x:
184+
self.parent[x] = self.parent[self.parent[x]]
185+
x = self.parent[x]
186+
return x
187+
188+
def union(self, x, y):
189+
ra = self.find(x)
190+
rb = self.find(y)
191+
192+
if ra == rb:
193+
return
194+
195+
if self.size[ra] < self.size[rb]:
196+
ra, rb = rb, ra
197+
198+
self.parent[rb] = ra
199+
self.size[ra] += self.size[rb]
200+
201+
def component_size(self, x):
202+
return self.size[self.find(x)]
203+
204+
205+
def solve():
206+
[n, m, q] = list_ints()
207+
dsu = DSU(n)
208+
for i in range(m):
209+
[u, v] = list_ints()
210+
dsu.union(u, v)
211+
212+
for _ in range(q):
213+
query_list = list_ints()
214+
if len(query_list) == 2:
215+
write_line(dsu.component_size(query_list[1]))
216+
else:
217+
if dsu.find(query_list[1]) == dsu.find(query_list[2]):
218+
write_line("YES")
219+
else:
220+
write_line("NO")
221+
222+
223+
if __name__ == "__main__":
224+
solve()
225+
226+
"""
227+
✅ Time Complexity
228+
Each union / find: O(α(N)) (inverse Ackermann, ~constant)
229+
Processing edges: O(M α(N))
230+
Each query: O(α(N))
231+
232+
👉 Total:
233+
234+
O((N+M+Q)α(N))≈O(N+M+Q)
235+
✅ Space Complexity
236+
Parent array: O(N)
237+
Size array: O(N)
238+
239+
👉 Total:
240+
241+
O(N)
242+
"""
Lines changed: 117 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# https://maang.in/problems/Find-the-Number-of-Rooms-191?resourceUrl=cs214-cp873-pl3337-rs191&returnUrl=%5B%22%2Fcourses%2FGraph-Level-1-214%3Ftab%3Dchapters%22%5D
2+
3+
"""
4+
Description
5+
You are given a map of a building, and your task is to count the number of its rooms. The size of the map is n×m squares, and each square is either floor or wall. You can walk left, right, up, and down through the floor squares. Each character in the map is either
6+
7+
Defination of Room : A maximal connected group of floor cells (.), where connectivity is only through up, down, left, or right moves.
8+
9+
Input Format
10+
The first input line has two integers n and m: the height and width of the map. Then there are n lines of m characters describing the map.
11+
12+
Output Format
13+
Print one integer: the number of rooms.
14+
15+
Constraints
16+
1≤n,m≤1000
17+
18+
Sample Input 1
19+
5 8
20+
########
21+
#..#...#
22+
####.#.#
23+
#..#...#
24+
########
25+
Sample Output 1
26+
3
27+
Note
28+
29+
"""
30+
31+
# Write your code here
32+
33+
import sys
34+
from collections import defaultdict
35+
36+
input = sys.stdin.readline
37+
print = sys.stdout.write
38+
sys.setrecursionlimit(1 << 25)
39+
40+
MOD = 10**9 + 7
41+
INF = 10**18
42+
43+
44+
def read():
45+
return sys.stdin.buffer.read()
46+
47+
48+
def ints():
49+
return map(int, input().split())
50+
51+
52+
def list_ints():
53+
return list(map(int, input().split()))
54+
55+
56+
def write_line(value=""):
57+
sys.stdout.write(str(value) + "\n")
58+
59+
60+
def write_lines(values):
61+
sys.stdout.write("\n".join(map(str, values)))
62+
if values:
63+
sys.stdout.write("\n")
64+
65+
66+
direction = [(1, 0), (0, 1), (-1, 0), (0, -1)]
67+
68+
69+
def dfs(x, y, grid, n, m, vis):
70+
# if vis[x][y]:
71+
# return
72+
# vis[x][y] = True
73+
# for dx, dy in direction:
74+
# nx, ny = x + dx, y + dy
75+
# if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == ".":
76+
# dfs(nx, ny, grid, n, m,vis)
77+
78+
stack = [(x, y)]
79+
vis[x][y] = True
80+
81+
while stack:
82+
x, y = stack.pop()
83+
for dx, dy in direction:
84+
nx, ny = x + dx, y + dy
85+
if (
86+
0 <= nx < n
87+
and 0 <= ny < m
88+
and grid[nx][ny] == "."
89+
and vis[nx][ny] == False
90+
):
91+
vis[nx][ny] = True
92+
stack.append((nx, ny))
93+
94+
95+
def solve():
96+
[n, m] = list_ints()
97+
grid = []
98+
for _ in range(n):
99+
grid.append(input().strip())
100+
101+
vis = [[False] * m for _ in range(n)]
102+
component = 0
103+
for i in range(n):
104+
for j in range(m):
105+
if not vis[i][j] and grid[i][j] == ".":
106+
dfs(i, j, grid, n, m, vis)
107+
component += 1
108+
write_line(component)
109+
110+
111+
if __name__ == "__main__":
112+
solve()
113+
114+
115+
"""
116+
Time Complexity per test case: O(n×m). Space Complexity per test case: O(n×m) for the visited array and recursion stack.
117+
"""

0 commit comments

Comments
 (0)