-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathInfectionDistribution.java
146 lines (121 loc) · 4.97 KB
/
InfectionDistribution.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package by.andd3dfx.common;
import lombok.Data;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
/**
* <pre>
* В королевстве есть несколько городов, соединенных дорогами. Города называются соседними, если между ними есть прямая
* дорога. Первоначально чума вспыхнула лишь в паре городов, однако каждую неделю соседние города чумного города также
* подвергались заражению и становились чумными.
* Задача определить через сколько недель все королевство будет заражено.
*
* Input:
* - cities_amount: n
* - roads: [[n_i, n_j], ...]
* - infected: [m_1, m_2, ...]
*
* Output:
* weeks_count
* </pre>
*
* @see <a href="https://youtu.be/Ei1uCCD_Iqg">Video solution</a>
*/
public class InfectionDistribution {
/**
* Initial solution
*/
public static int weeksToInfectAllCities_usingIterationByRoads(int citiesAmount, int[][] roads, int[] infected) {
int weeksCount = 0;
var infectedCitiesSet = Arrays.stream(infected).boxed()
.collect(Collectors.toSet());
var roadsSet = buildRoadsSet(roads);
while (!isAllInfected(citiesAmount, infectedCitiesSet)) {
var infectedOnThisIteration = processOneWeek(roadsSet, infectedCitiesSet);
if (infectedOnThisIteration == 0) {
throw new IllegalArgumentException("Could not infect all cities!");
}
weeksCount++;
}
return weeksCount;
}
private static boolean isAllInfected(int citiesAmount, Set<Integer> infectedCitiesSet) {
return infectedCitiesSet.size() == citiesAmount;
}
private static Set<Road> buildRoadsSet(int[][] roads) {
return Arrays.stream(roads)
.map(Road::new)
.collect(Collectors.toSet());
}
private static int processOneWeek(Set<Road> roads, Set<Integer> infectedCitiesSet) {
var initialCitiesSet = new HashSet<>(infectedCitiesSet);
var it = roads.iterator();
while (it.hasNext()) {
var road = it.next();
if (initialCitiesSet.contains(road.start)) {
infectedCitiesSet.add(road.end);
it.remove();
continue;
}
if (initialCitiesSet.contains(road.end)) {
infectedCitiesSet.add(road.start);
it.remove();
}
}
return infectedCitiesSet.size() - initialCitiesSet.size();
}
@Data
private static class Road {
private int start;
private int end;
public Road(int[] road) {
this.start = road[0];
this.end = road[1];
}
}
/**
* Enhanced solution
*/
public static int weeksToInfectAllCities_usingIterationByInfectedCities(int citiesAmount, int[][] roads, int[] infected) {
var routesMap = new HashMap<Integer, Set<Integer>>();
Arrays.stream(roads).forEach(road -> {
populate(routesMap, road, 0, 1);
populate(routesMap, road, 1, 0);
});
var weeksAmount = 0;
var infectedCities = Arrays.stream(infected).boxed().collect(Collectors.toSet());
var sourceCities = new HashSet<>(infectedCities);
while (!isAllInfected(citiesAmount, infectedCities)) {
if (sourceCities.isEmpty()) {
throw new IllegalArgumentException("Could not infect all cities!");
}
var newInfectedCities = determineNewInfectedCities(routesMap, infectedCities, sourceCities);
infectedCities.addAll(newInfectedCities);
sourceCities = newInfectedCities;
weeksAmount++;
}
return weeksAmount;
}
private static HashSet<Integer> determineNewInfectedCities(
Map<Integer, Set<Integer>> routesMap, Set<Integer> infectedCities, Set<Integer> sourceCities) {
var newInfectedCities = new HashSet<Integer>();
for (var city : sourceCities) {
if (!routesMap.containsKey(city)) {
continue;
}
var citiesToInfect = new HashSet<>(routesMap.get(city));
citiesToInfect.removeAll(infectedCities);
newInfectedCities.addAll(citiesToInfect);
}
return newInfectedCities;
}
private static void populate(Map<Integer, Set<Integer>> routesMap, int[] road, int i, int j) {
if (!routesMap.containsKey(road[i])) {
routesMap.put(road[i], new HashSet<>());
}
routesMap.get(road[i]).add(road[j]);
}
}