-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSum_Of_Minimum_Connected_Component.java
More file actions
70 lines (65 loc) · 1.3 KB
/
Sum_Of_Minimum_Connected_Component.java
File metadata and controls
70 lines (65 loc) · 1.3 KB
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
//Sources
//https://www.geeksforgeeks.org/sum-of-the-minimum-elements-in-all-connected-components-of-an-undirected-graph/
import java.util.LinkedList;
import java.util.Scanner;
class Sum_Of_Minimum_Connected_Component
{
int v;
LinkedList<Integer> adj[];
boolean []visited;
Sum_Of_Minimum_Connected_Component(int v)
{
this.v=v;
adj=new LinkedList[v];
visited=new boolean[v];
for(int i=0;i<v;i++)
{
adj[i]=new LinkedList<>();
}
}
void addEdge(int src,int dest)
{
adj[src].add(dest);
adj[dest].add(src);
}
void dfsUtil(int node,int a[],int m)
{
m=Math.min(m,a[node]);
visited[node]=true;
for(Integer i:adj[node])
{
if(!visited[i])
dfsUtil(i,a,m);
}
}
void dfs(int []a)
{
int sum=0;
for(int i=0;i<v;i++)
{
if(!visited[i])
{
int m=a[i];
dfsUtil(i,a,m);
sum+=m;
}
}
System.out.println(sum);
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int v=sc.nextInt();
int []a=new int[v];
for(int i=0;i<v;i++)
a[i]=sc.nextInt();
int e=sc.nextInt();
Sum_Of_Minimum_Connected_Component g=new Sum_Of_Minimum_Connected_Component(v);
for(int i=1;i<=e;i++)
{
int src=sc.nextInt();
int dest=sc.nextInt();
g.addEdge(src,dest);
}
g.dfs(a);
}
}