Created
October 29, 2014 03:14
-
-
Save josephliccini/478ca26b36d7e8e0b8dd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.ArrayList; | |
import java.util.HashMap; | |
import java.util.LinkedList; | |
import java.util.List; | |
import java.util.Map; | |
import java.util.Scanner; | |
public class FacebookQuestion { | |
public static void main(String[] args) { | |
Scanner sc = new Scanner(System.in); | |
Map<String, Node> allNodes = new HashMap<String, Node>(); | |
int numPairs = sc.nextInt(); | |
for(int i = 0; i < numPairs; ++i) { | |
String left = sc.next(); | |
String right = sc.next(); | |
Node parent = null; | |
Node dep = null; | |
if ((allNodes.containsKey(left))) | |
parent =allNodes.get(left); | |
else | |
parent = new Node(left); | |
if ((allNodes.containsKey(right))) | |
dep =allNodes.get(right); | |
else | |
dep = new Node(right); | |
dep.isHead = false; | |
parent.addDependency(dep); | |
allNodes.put(left, parent); | |
allNodes.put(right, dep); | |
} | |
List<LinkedList<Node>> list = new ArrayList<LinkedList<Node>>(); | |
for(Node n: allNodes.values()) { | |
LinkedList<Node> nodeList = new LinkedList<Node>(); | |
if (n.isHead) { | |
Node crawl = n; | |
while(crawl.dependency != null) { | |
nodeList.add(crawl); | |
crawl = crawl.dependency; | |
} | |
nodeList.add(crawl); | |
list.add(nodeList); | |
} | |
} | |
System.out.println(list.toString()); | |
} | |
} | |
class Node { | |
Node dependency; | |
String name; | |
boolean isHead = true; | |
public Node(String name) { | |
this.name = name; | |
dependency = null; | |
} | |
public void addDependency(Node dep) { | |
this.dependency = dep; | |
} | |
@Override | |
public boolean equals(Object other) { | |
Node otherNode = (Node)other; | |
return otherNode.name.equals(this.name); | |
} | |
@Override | |
public String toString() { | |
return this.name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice. Much much much cleaner than my solution: https://gist.github.com/dejesus2010/5ff415f99898c378ee87