-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwheel.java
More file actions
85 lines (62 loc) · 1.78 KB
/
wheel.java
File metadata and controls
85 lines (62 loc) · 1.78 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
import java.util.*;
import java.io.*;
class Word {
String word;
int inEdges = 0;
int path = 0;
public Word(String word) {
this.word = word;
}
}
public class wheel {
public static void main(String[] args) throws IOException {
BufferedReader f = new BufferedReader(new FileReader("wheel.in"));
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("output.out")));
int cases = Integer.parseInt(f.readLine());
for (int puzzle = 1; puzzle <= cases; puzzle++)
{
int phrases = Integer.parseInt(f.readLine());
HashMap<String , HashSet<String>> graph = new HashMap<>();
HashMap<String , Word> map = new HashMap<>();
for (int i = 0; i < phrases; i++)
{
String phrase = f.readLine();
String word1 = phrase.substring(0 , phrase.indexOf(" "));
String word2 = phrase.substring(phrase.lastIndexOf(" ") + 1);
if (!map.containsKey(word1))
{
graph.put(word1 , new HashSet<>());
map.put(word1 , new Word(word1));
}
if (!map.containsKey(word2))
{
graph.put(word2 , new HashSet<>());
map.put(word2 , new Word(word2));
}
graph.get(word1).add(word2);
map.get(word2).inEdges += 1;
}
ArrayDeque<Word> queue = new ArrayDeque<>();
int maxPath = 0;
for (String word : graph.keySet())
if (map.get(word).inEdges == 0)
queue.add(map.get(word));
while (!queue.isEmpty())
{
Word current = queue.remove();
for (String x : graph.get(current.word))
{
Word check = map.get(x);
check.path = Math.max(check.path , current.path + 1);
maxPath = Math.max(maxPath , check.path);
check.inEdges -= 1;
if (check.inEdges == 0)
queue.add(check);
}
}
out.println("Puzzle #" + puzzle + ": " + maxPath);
}
f.close();
out.close();
}
}