-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path27.java
111 lines (100 loc) · 2.59 KB
/
27.java
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
109
110
111
//{ Driver Code Starts
import java.util.*;
import java.lang.*;
import java.io.*;
class GFG
{
public static void main(String[] args) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine().trim());
while(T-->0)
{
String[] s = br.readLine().trim().split(" ");
int V = Integer.parseInt(s[0]);
int E = Integer.parseInt(s[1]);
ArrayList<ArrayList<Integer>>adj = new ArrayList<>();
for(int i = 0; i < V; i++)
adj.add(i, new ArrayList<Integer>());
for(int i = 0; i < E; i++){
String[] S = br.readLine().trim().split(" ");
int u = Integer.parseInt(S[0]);
int v = Integer.parseInt(S[1]);
adj.get(u).add(v);
adj.get(v).add(u);
}
Solution obj = new Solution();
int ans = obj.detectCycle(V, adj);
System.out.println(ans);
}
}
}
// } Driver Code Ends
class Solution
{
//Function to detect cycle using DSU in an undirected graph.
public int detectCycle(int V, ArrayList<ArrayList<Integer>> adj)
{
// Code here
if(V == 2) return 0;
HashSet<String> h=new HashSet<>();
Disjoint d = new Disjoint(V);
for (int i = 0; i < V; i++) {
for (int j = 0; j < adj.get(i).size(); j++) {
int v = adj.get(i).get(j);
int u=i;
if (d.fup(u) == d.fup(v) && h.contains(fun(u,v))==false) {
return 1;
} else {
d.union(u, v);
h.add(fun(u,v));
h.add(fun(v,u));
}
}
}
return 0;
}
static String fun(int u,int v)
{
String ans=Integer.toString(u);
ans+=Integer.toString(v);
return ans;
}
}
class Disjoint
{
int[] sz;
int[] pr;
Disjoint(int n)
{
pr=new int[n+1];
sz=new int[n+1];
for(int i=0;i<=n;i++)
{
pr[i]=i;
sz[i]=1;
}
}
int fup(int node)
{
if(node==pr[node])
return node;
return pr[node]=fup(pr[node]);
}
void union(int u,int v)
{
int up=fup(u);
int vp=fup(v);
if(u==v) return;
if(sz[up]>sz[vp])
{
sz[up]=sz[up]+sz[vp];
pr[vp]=pr[up];
}
else
{
sz[vp]=sz[up]+sz[vp];
pr[up]=pr[vp];
}
}
}