-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumarare.java
More file actions
89 lines (75 loc) · 2.41 KB
/
Numarare.java
File metadata and controls
89 lines (75 loc) · 2.41 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
public class Numarare {
private static final int MOD = 1000000007;
private static class FastScanner {
BufferedReader br;
StringTokenizer st;
public FastScanner(String fileName) throws FileNotFoundException {
br = new BufferedReader(new FileReader(fileName));
}
String next() throws IOException {
while (st == null || !st.hasMoreTokens()) {
st = new StringTokenizer(br.readLine());
}
return st.nextToken();
}
int nextInt() throws IOException {
return Integer.parseInt(next());
}
void close() throws IOException {
br.close();
}
}
public static void main(String[] args) throws IOException {
String inputFileName = "numarare.in";
String outputFileName = "numarare.out";
FastScanner scanner = new FastScanner(inputFileName);
int N = scanner.nextInt();
int M = scanner.nextInt();
// Create lists to store the graphs as sets of edges
List<Set<Integer>> graph1 = new ArrayList<>();
List<Set<Integer>> graph2 = new ArrayList<>();
for (int i = 0; i <= N; i++) {
graph1.add(new HashSet<>());
graph2.add(new HashSet<>());
}
for (int i = 0; i < M; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
graph1.get(x).add(y);
}
for (int i = 0; i < M; i++) {
int x = scanner.nextInt();
int y = scanner.nextInt();
graph2.get(x).add(y);
}
scanner.close();
int[] dp = new int[N + 1];
dp[1] = 1; // Base case: there is one elementary chain of length 0 from node 1 to itself
for (int node = 1; node < N; node++) {
// If there is at least one elementary chain reaching node 'node'
if (dp[node] > 0) {
// Check if the neighbors of 'node' in graph1 are also neighbors in graph2
for (int neighbor : graph1.get(node)) {
if (graph2.get(node).contains(neighbor)) {
// Update the count of elementary chains reaching 'neighbor'
dp[neighbor] = (dp[neighbor] + dp[node]) % MOD;
}
}
}
}
try (BufferedWriter writer = new BufferedWriter(new FileWriter(outputFileName))) {
writer.write(Integer.toString(dp[N]));
}
}
}