forked from improper4/uva
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UVa00336_ANodeTooFar.java
96 lines (77 loc) · 2.07 KB
/
UVa00336_ANodeTooFar.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
package uva;
/* USER: 46724 (sfmunera) */
/* PROBLEM: 272 (336 - A Node Too Far) */
/* SUBMISSION: 09048940 */
/* SUBMISSION TIME: 2011-07-14 17:55:05 */
/* LANGUAGE: 2 */
import java.util.*;
import java.io.*;
public class UVa00336_ANodeTooFar {
static Map<Integer, Integer> vertices;
static boolean[][] G;
static int N;
static int[] bfs(int source) {
int[] distance = new int[N];
boolean[] visited = new boolean[N];
int[] parent = new int[N];
Arrays.fill(distance, -1);
Arrays.fill(parent, -1);
Queue<Integer> Q = new LinkedList<Integer>();
Q.offer(source);
int i = vertices.get(source);
visited[i] = true;
distance[i] = 0;
while (!Q.isEmpty()) {
int v = Q.poll();
i = vertices.get(v);
for (int w : vertices.keySet()) {
int j = vertices.get(w);
if (G[i][j] && !visited[j]) {
visited[j] = true;
distance[j] = distance[i] + 1;
parent[j] = v;
Q.offer(w);
}
}
}
return distance;
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
int t = 1;
while (true) {
int NC = in.nextInt();
if (NC == 0)
break;
vertices = new HashMap<Integer, Integer>();
G = new boolean[50][50];
N = 0;
for (int i = 0; i < NC; ++i) {
int from = in.nextInt();
int to = in.nextInt();
if (!vertices.containsKey(from))
vertices.put(from, N++);
if (!vertices.containsKey(to))
vertices.put(to, N++);
G[vertices.get(to)][vertices.get(from)] =
G[vertices.get(from)][vertices.get(to)] = true;
}
while (true) {
int source = in.nextInt();
int ttl = in.nextInt();
if (source == 0 && ttl == 0)
break;
int[] distance = bfs(source);
int cnt = 0;
for (int x : distance)
if (x == -1 || x > ttl)
++cnt;
System.out.println("Case " + t + ": " + cnt + " nodes not reachable from node " +
source + " with TTL = " + ttl + ".");
++t;
}
}
in.close();
System.exit(0);
}
}