-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimplePaths.java
More file actions
46 lines (38 loc) · 1001 Bytes
/
SimplePaths.java
File metadata and controls
46 lines (38 loc) · 1001 Bytes
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
import java.util.*;
public class SimplePaths {
public static int findPaths(ArrayList<Integer>[] edges) {
HashSet<Integer> visited=new HashSet<Integer>();
Queue<Integer> toVisit=new LinkedList<Integer>();
toVisit.add(1);
int total=0;
int current;
while(!toVisit.isEmpty()){
current=toVisit.poll();
visited.add(current);
int unvisited=0;
for(int vertex: edges[current]) {
if(!visited.contains(vertex))
{
unvisited++;
toVisit.offer(vertex);
}
}
int nEdges=edges[current].size();
total= nEdges + total * nEdges * unvisited;
}
return total;
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int t=sc.nextInt();
for(int i=0;i<t;i++) {
int n=sc.nextInt();
var graph=new ArrayList<Integer>[ n+1 ];
for(int j=0;j<n;j++)
graph[j]=new ArrayList<Integer>();
for(int j=0;j<n;j++)
graph[sc.nextInt()].add(sc.nextInt());
System.out.println(findPaths(graph));
}
}
}