-
Notifications
You must be signed in to change notification settings - Fork 0
/
switcheroo.java
83 lines (80 loc) · 1.75 KB
/
switcheroo.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
import java.util.Arrays;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class Grapht{
public int V;
public int[] color;
public int[] colorx;
public int[] d ;
public int[] pi ;
public int[] time;
public int timeM = 1;
Queue<Integer> queue = new LinkedList<>();
public LinkedList<Integer> adj[];
Grapht(int v){
timeM = 0;
V = v;
d = new int[v + 1];
pi = new int[v + 1];
color = new int[v + 1];
colorx = new int[v + 1];
time = new int[v + 1];
adj = new LinkedList[v + 1];
for (int i = 0; i < v + 1; i++) {
adj[i] = new LinkedList();
}
}
public void addEdge(int v, int w) {
adj[v].add(w);
}
public void dfsUtil(int jk) {
color[jk] = 1;
time[jk] = timeM;
timeM += 1;
Iterator<Integer> iter = adj[jk].listIterator();
while (iter.hasNext()) {
int kd = iter.next();
if (color[kd] == 0) {
dfsUtil(kd);
}
}
}
public void DFS(int t) {
Iterator<Integer> iter = adj[t].listIterator();
while (iter.hasNext()) {
int kk = iter.next();
if (color[kk] == 0) {
dfsUtil(kk);
}
}
color = colorx.clone();
// System.out.println("COLORS: " + Arrays.toString(color));
timeM = 1;
}
}
public class isDistanceEqual {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int a = scan.nextInt();
for (int i = 0; i < a; i++) {
int b = scan.nextInt();
Grapht g = new Grapht(b);
int[] c = new int[b];
for (int j = 0; j < b; j++) {
c[j] = scan.nextInt();
g.addEdge(j + 1, c[j]);
}
for (int j = 0; j < b; j++) {
g.DFS(j + 1);
if (j == 0) {
int kh = g.time[1] + 1;
System.out.print(kh + " ");}
else {
System.out.print(g.time[j + 1] + " ");}
}
System.out.println("");
}
}
}