-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGraphs-Roads and Libraries.py
69 lines (48 loc) · 1.26 KB
/
Graphs-Roads and Libraries.py
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
#Problem Link : https://www.hackerrank.com/challenges/torque-and-development/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=graphs
#Ans:
#!/bin/python3
import math
import os
import random
import re
import sys
#
# Complete the 'roadsAndLibraries' function below.
#
# The function is expected to return a LONG_INTEGER.
# The function accepts following parameters:
# 1. INTEGER n
# 2. INTEGER c_lib
# 3. INTEGER c_road
# 4. 2D_INTEGER_ARRAY cities
#
from collections import defaultdict
def walk(g, v, used):
used[v] = True
count = 1
for u in g[v]:
if not used[u]:
count += walk(g, u, used)
return count
def solve():
n, m, c_lib, c_road = map(int, input().split())
g = defaultdict(set)
for _ in range(m):
u, v = map(int, input().split())
g[u].add(v)
g[v].add(u)
if c_lib <= c_road:
return n * c_lib
answer = 0
used = [False] * (n + 1)
for v in range(1, n + 1):
if not used[v]:
cities = walk(g, v, used)
answer += c_lib + (cities - 1) * c_road
return answer
def main():
q = int(input())
for _ in range(q):
print(solve())
if __name__ == '__main__':
main()