Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitf17da57

Browse files
committed
Implementation Google level 4 second challenge.
Dinic`s algorithm implemented as solution which passes the tests.Finding more efficient solution is in progress.
1 parentfd1dedf commitf17da57

File tree

2 files changed

+565
-267
lines changed

2 files changed

+565
-267
lines changed

‎src/google/Level4/Challenge2/README.md‎

Lines changed: 277 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ es# Problem
33
Escape Pods
44
===========
55

6-
You've blown up the LAMBCHOP doomsday device and broken the bunnies out of Lambda's prison - and now you need to escape from the space station as quickly and as orderly as possible! The bunnies have all gathered in various locations throughout the station, and need to make their way towards the seemingly endless amount of escape pods positioned in other parts of the station. You need to get the numerous bunnies through the various rooms to the escape pods. Unfortunately, the corridors between the rooms can only fit so many bunnies at a time. What's more, many of the corridors were resized to accommodate the LAMBCHOP, so they vary in how many bunnies can move through them at a time.
6+
You've blown up the LAMBCHOP doomsday device and broken the bunnies out of Lambda's prison - and now you need to escape from the space station as quickly and as orderly as possible! The bunnies have all gathered in various locations throughout the station, and need to make their way towards the seemingly endless amount of escape pods positioned in other parts of the station. You need to get the numerous bunnies through the various rooms to the escape pods. Unfortunately, the corridors between the rooms can only fit so many bunnies at a time. What's more, many of the corridors were resized to accommodate the LAMBCHOP, so they vary in how many bunnies can move through them at a time.
77

88
Given the starting room numbers of the groups of bunnies, the room numbers of the escape pods, and how many bunnies can fit through at a time in each direction of every corridor in between, figure out how many bunnies can safely make it to the escape pods at a time at peak.
99

@@ -68,7 +68,6 @@ Use verify [file] to test your solution and see how it does. When you are finish
6868
#Solution
6969

7070
##Analysis
71-
###First Example
7271
For example, if you have:
7372
Entrances =[0, 1]
7473
Exits =[4, 5]
@@ -118,7 +117,7 @@ The problem is related to finding the network flow.
118117

119118
###Theory
120119
-https://algs4.cs.princeton.edu/40graphs
121-
-[Network Flow Algorithms Starting Here](https://www.youtube.com/watch?v=LdOnanfc5TM&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=33&t=3s)
120+
-[Network Flow Algorithms Starting Here](https://www.youtube.com/watch?v=LdOnanfc5TM&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=33)
122121
-13. Incremental Improvement: Max Flow, Min Cut](https://www.youtube.com/watch?v=VYZGlgzr_As)
123122
-14.https://www.youtube.com/watch?v=8C_T4iTzPCU
124123
-https://www.youtube.com/watch?v=0CdxkgAjsDA
@@ -130,7 +129,8 @@ The problem is related to finding the network flow.
130129
-https://stackoverflow.com/questions/36054690/how-to-use-dinics-algorithm-to-find-min-cut-edges-in-undireted-graph
131130
- Actual Complexity of Max Flow Algorithmshttps://codeforces.com/blog/entry/52714
132131

133-
Functional example:
132+
133+
###First Example
134134

135135
```java
136136

@@ -222,9 +222,11 @@ public class EscapePods {
222222
return solveWithFordFulkerson(transform(entrances, exits, path));
223223
}
224224
}
225-
```
225+
```
226+
###Dinic's Algorithm
227+
From further research, a more efficient algorithm - Dinic's algorithm selected.
226228

227-
###Understanding Dinic's
229+
#####Theory
228230
-https://en.wikipedia.org/wiki/Dinic%27s_algorithm
229231
-https://www.youtube.com/watch?v=M6cm8UeeziI&list=PLDV1Zeh2NRsDGO4--qE8yH72HFL1Km93P&index=42
230232
-https://github.com/ADJA/algos/blob/master/Graphs/Dinic.cpp
@@ -235,50 +237,275 @@ public class EscapePods {
235237
-https://github.com/nkapliev/google-foo.bar/blob/master/problems/4.2_escape_pods.py
236238
-http://www.cs.ust.hk/mjg_lib/Classes/COMP572_Fall07/Notes/index.htm
237239

240+
#####Example Implementation
241+
```java
242+
/**
243+
* Implementation of Dinic's network flow algorithm. The algorithm works by first constructing a
244+
* level graph using a BFS and then finding augmenting paths on the level graph using multiple DFSs.
245+
*
246+
* <p>Time Complexity: O(EV²)
247+
*
248+
* <p>Download the code: $ git clone https://github.com/williamfiset/Algorithms
249+
*
250+
* <p>Change directory to the root of the Algorithms directory: $ cd Algorithms
251+
*
252+
* <p>Build: $ javac -d src/main/java
253+
* src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/examples/DinicsExample.java
254+
*
255+
* <p>Run: $ java -cp src/main/java
256+
* com/williamfiset/algorithms/graphtheory/networkflow/examples/DinicsExample
257+
*/
258+
packagecom.williamfiset.algorithms.graphtheory.networkflow.examples;
259+
260+
import staticjava.lang.Math.min;
261+
262+
importjava.util.*;
263+
264+
publicclassDinicsExample {
265+
266+
privatestaticclassEdge {
267+
publicint from, to;
268+
publicEdge residual;
269+
publiclong flow;
270+
publicfinallong capacity;
271+
272+
publicEdge(intfrom,intto,longcapacity) {
273+
this.from= from;
274+
this.to= to;
275+
this.capacity= capacity;
276+
}
277+
278+
publicbooleanisResidual() {
279+
return capacity==0;
280+
}
281+
282+
publiclongremainingCapacity() {
283+
return capacity- flow;
284+
}
285+
286+
publicvoidaugment(longbottleNeck) {
287+
flow+= bottleNeck;
288+
residual.flow-= bottleNeck;
289+
}
290+
291+
publicStringtoString(ints,intt) {
292+
String u= (from== s)?"s": ((from== t)?"t":String.valueOf(from));
293+
String v= (to== s)?"s": ((to== t)?"t":String.valueOf(to));
294+
returnString.format(
295+
"Edge %s -> %s | flow = %3d | capacity = %3d | is residual: %s",
296+
u, v, flow, capacity, isResidual());
297+
}
298+
}
299+
300+
privateabstractstaticclassNetworkFlowSolverBase {
301+
302+
// To avoid overflow, set infinity to a value less than Long.MAX_VALUE;
303+
staticfinallongINF=Long.MAX_VALUE/2;
304+
305+
// Inputs: n = number of nodes, s = source, t = sink
306+
finalint n, s, t;
307+
308+
// Indicates whether the network flow algorithm has ran. The solver only
309+
// needs to run once because it always yields the same result.
310+
protectedboolean solved;
311+
312+
// The maximum flow. Calculated by calling the {@link #solve} method.
313+
protectedlong maxFlow;
314+
315+
// The adjacency list representing the flow graph.
316+
protectedList<Edge>[] graph;
317+
318+
/**
319+
* Creates an instance of a flow network solver. Use the {@link #addEdge} method to add edges to
320+
* the graph.
321+
*
322+
*@param n - The number of nodes in the graph including s and t.
323+
*@param s - The index of the source node, 0 <= s < n
324+
*@param t - The index of the sink node, 0 <= t < n and t != s
325+
*/
326+
publicNetworkFlowSolverBase(intn,ints,intt) {
327+
this.n= n;
328+
this.s= s;
329+
this.t= t;
330+
initializeEmptyFlowGraph();
331+
}
332+
333+
// Constructs an empty graph with n nodes including s and t.
334+
@SuppressWarnings("unchecked")
335+
privatevoidinitializeEmptyFlowGraph() {
336+
graph=newList[n];
337+
for (int i=0; i< n; i++) graph[i]=newArrayList<Edge>();
338+
}
339+
340+
/**
341+
* Adds a directed edge (and its residual edge) to the flow graph.
342+
*
343+
*@param from - The index of the node the directed edge starts at.
344+
*@param to - The index of the node the directed edge ends at.
345+
*@param capacity - The capacity of the edge
346+
*/
347+
publicvoidaddEdge(intfrom,intto,longcapacity) {
348+
if (capacity<=0)thrownewIllegalArgumentException("Forward edge capacity <= 0");
349+
Edge e1=newEdge(from, to, capacity);
350+
Edge e2=newEdge(to, from,0);
351+
e1.residual= e2;
352+
e2.residual= e1;
353+
graph[from].add(e1);
354+
graph[to].add(e2);
355+
}
356+
357+
/**
358+
* Returns the residual graph after the solver has been executed. This allows you to inspect the
359+
* {@link Edge#flow} and {@link Edge#capacity} values of each edge. This is useful if you are
360+
* debugging or want to figure out which edges were used during the max flow.
361+
*/
362+
publicList<Edge>[]getGraph() {
363+
execute();
364+
return graph;
365+
}
366+
367+
// Returns the maximum flow from the source to the sink.
368+
publiclonggetMaxFlow() {
369+
execute();
370+
return maxFlow;
371+
}
372+
373+
// Wrapper method that ensures we only call solve() once
374+
privatevoidexecute() {
375+
if (solved)return;
376+
solved=true;
377+
solve();
378+
}
379+
380+
// Method to implement which solves the network flow problem.
381+
publicabstractvoidsolve();
382+
}
383+
384+
privatestaticclassDinicsSolverextendsNetworkFlowSolverBase {
385+
386+
privateint[] level;
387+
388+
/**
389+
* Creates an instance of a flow network solver. Use the {@link #addEdge} method to add edges to
390+
* the graph.
391+
*
392+
*@param n - The number of nodes in the graph including source and sink nodes.
393+
*@param s - The index of the source node, 0 <= s < n
394+
*@param t - The index of the sink node, 0 <= t < n, t != s
395+
*/
396+
publicDinicsSolver(intn,ints,intt) {
397+
super(n, s, t);
398+
level=newint[n];
399+
}
400+
401+
@Override
402+
publicvoidsolve() {
403+
// next[i] indicates the next edge index to take in the adjacency list for node i. This is
404+
// part
405+
// of the Shimon Even and Alon Itai optimization of pruning deads ends as part of the DFS
406+
// phase.
407+
int[] next=newint[n];
408+
409+
while (bfs()) {
410+
Arrays.fill(next,0);
411+
// Find max flow by adding all augmenting path flows.
412+
for (long f= dfs(s, next,INF); f!=0; f= dfs(s, next,INF)) {
413+
maxFlow+= f;
414+
}
415+
}
416+
}
417+
418+
// Do a BFS from source to sink and compute the depth/level of each node
419+
// which is the minimum number of edges from that node to the source.
420+
privatebooleanbfs() {
421+
Arrays.fill(level,-1);
422+
Deque<Integer> q=newArrayDeque<>(n);
423+
q.offer(s);
424+
level[s]=0;
425+
while (!q.isEmpty()) {
426+
int node= q.poll();
427+
for (Edge edge: graph[node]) {
428+
long cap= edge.remainingCapacity();
429+
if (cap>0&& level[edge.to]==-1) {
430+
level[edge.to]= level[node]+1;
431+
q.offer(edge.to);
432+
}
433+
}
434+
}
435+
// Return whether we were able to reach the sink node.
436+
return level[t]!=-1;
437+
}
438+
439+
privatelongdfs(intat,int[]next,longflow) {
440+
if (at== t)return flow;
441+
finalint numEdges= graph[at].size();
442+
443+
for (; next[at]< numEdges; next[at]++) {
444+
Edge edge= graph[at].get(next[at]);
445+
long cap= edge.remainingCapacity();
446+
if (cap>0&& level[edge.to]== level[at]+1) {
447+
448+
long bottleNeck= dfs(edge.to, next, min(flow, cap));
449+
if (bottleNeck>0) {
450+
edge.augment(bottleNeck);
451+
return bottleNeck;
452+
}
453+
}
454+
}
455+
return0;
456+
}
457+
}
458+
459+
publicstaticvoidmain(String[]args) {
460+
int n=11;
461+
int s= n-1;
462+
int t= n-2;
463+
464+
NetworkFlowSolverBase solver;
465+
solver=newDinicsSolver(n, s, t);
466+
467+
// Source edges
468+
solver.addEdge(s,0,5);
469+
solver.addEdge(s,1,10);
470+
solver.addEdge(s,2,15);
471+
472+
// Middle edges
473+
solver.addEdge(0,3,10);
474+
solver.addEdge(1,0,15);
475+
solver.addEdge(1,4,20);
476+
solver.addEdge(2,5,25);
477+
solver.addEdge(3,4,25);
478+
solver.addEdge(3,6,10);
479+
solver.addEdge(4,2,5);
480+
solver.addEdge(4,7,30);
481+
solver.addEdge(5,7,20);
482+
solver.addEdge(5,8,10);
483+
solver.addEdge(7,8,15);
484+
485+
// Sink edges
486+
solver.addEdge(6, t,5);
487+
solver.addEdge(7, t,15);
488+
solver.addEdge(8, t,10);
489+
490+
// Prints: "Maximum flow: 30"
491+
System.out.printf("Maximum flow: %d\n", solver.getMaxFlow());
492+
}
493+
}
494+
495+
```
238496

497+
The pain point then was to use understand the algorithm to make it usable.
498+
The problem was to convert the adjacent graph into a graph with weighted
499+
edges. The first solution did not do that and the concept of extra source
500+
and sink nodes did not exits. Hence, to realize how to map the ends to
501+
those end required more analysis.
502+
Then, from going through the videos again and reviewing, it made more sense.
503+
The source and sink could be any indexes as along as entrances were directed
504+
from source and sink from the exits.
505+
Another realization that was made was that the adjacent matrix with value 0
506+
did not need to be converted into an edge. Only those with some value greater
507+
than 0 was transformed as edges of the graph.
239508

240-
######Tabs On Brower
241-
-[ ]https://www.hackerearth.com/practice/algorithms/graphs/shortest-path-algorithms/tutorial/
242-
-[ ]https://docs.ioin.in/writeup/www.auxy.xyz/_tutorial_Webkit_Exp_Tutorial_/index.html
243-
-[ ]https://tech.ebayinc.com/engineering/ou-online-analytical-processing/
244-
-[ ]https://www.linkedin.com/pulse/dos-donts-while-preparing-amazon-machine-learning-specialty-semaan/
245-
-[ ]https://www.infoq.com/podcasts/software-architecture-team-topologies
246-
-[ ]https://medium.com/awsblogs/ci-cd-with-kubernetes-3c29e8073c38
247-
-[ ]https://www.infoq.com/presentations/hotspot-graalvm-code-execution
248-
-[ ]https://medium.com/better-programming/modern-day-architecture-design-patterns-for-software-professionals-9056ee1ed977
249-
-[ ]https://www.linkedin.com/learning/cobol-essential-training/cobol-is-alive-and-well
250-
-[ ]https://mailchi.mp/5125b7b5305e/18-dear-architects
251-
-[ ]https://advocacy.vmware.com/member/post/1d9aff34-0610-42ed-9b90-21233cabc9ae?uc=113877&g=df4af070-be59-44be-b7f0-ea2387c55f98&f=2433965
252-
-[ ]https://minimatech.org/from-postgresql-to-neo4j
253-
-[ ]https://www.siddharthsarda.com/p/developer-progression-as-a-function
254-
-[ ]https://www.infoworld.com/article/3563829/jamstack-the-static-website-revolution-upending-web-development.html
255-
-[ ]https://apenwarr.ca/log/20201227 System design
256-
-[ ]https://www.infoq.com/articles/database-audit-system-kafka
257-
-[ ]https://increment.com/remote/committing-to-collaboration-version-control |https://increment.com/remote
258-
-[ ]https://medium.com/neotiv-gmbh/5-design-patterns-every-software-engineer-should-know-470c8b6c0b54
259-
-[ ]https://chromeisbad.com
260-
-[ ]https://vitaminac.github.io/Simple-Bootstrap-Linux-System/
261-
-[ ]https://hbr.org/2018/01/why-people-really-quit-their-jobs
262-
-[ ]https://play.picoctf.org/practice?category=6&page=1
263-
-[ ]https://architectelevator.com/architecture/famous-architects-sketch/
264-
-[ ]https://github.com/topjohnwu/Magisk
265-
-[ ]https://www.8bitmen.com/youtube-database-how-does-it-store-so-many-videos-without-running-out-of-storage-space/
266-
-[ ]https://github.com/facebook/zstd
267-
-[ ]https://github.com/topjohnwu/Magisk
268-
-[ ]https://tolisec.com/ssh-backdoor-botnet-with-research-infection-technique
269-
-[ ]https://www.infoq.com/articles/whats-the-next-step-for-data-management
270-
-[ ]https://opensource.com/
271-
-[ ]https://secret.club/2021/01/14/vbox-escape.html
272-
-[ ]https://www.linuxjournal.com/
273-
-[ ]https://www.weave.works/blog/the-gitops-pipeline
274-
-[ ]https://github.com/kubermatic/
275-
-[ ]https://github.com/open-telemetry/opentelemetry-go/contribute
276-
-[ ]https://github.com/SaturnsVoid/GoBot2
277-
-[ ]https://architectelevator.com/architecture/failure-doesnt-respect-abstraction/
278-
-[ ] Fast polynomial multiplication for programming contests (Java)https://www.davideisenstat.com/simplertimes
279-
-[ ]https://graphics.stanford.edu/~seander/bithacks.html |https://github.com/gibsjose/BitHacks
280-
-[ ]https://www.cs.cmu.edu/~15451-f18/lectures Download
281-
-[ ]https://www.vice.com/en/article/n7vqew/the-hacker-who-archived-parler-explains-how-she-did-it-and-what-comes-next
282-
-[ ]https://github.com/d0nk/parler-tricks
283-
-[ ]https://gist.github.com/Parler-Analysis/2c023fd2e053fba5bc85b09209f606eb
509+
The implementation was slightly modified as my implementation.
284510

511+
###Search For Better Algorithm

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp