有大佬做今早去哪儿的笔试题了吗?求分享

有大佬做今早去哪儿的笔试题了吗?求分享#去哪儿#
全部评论
就A了第二题 package Qunar; import java.util.ArrayList; import java.util.HashSet; import java.util.Scanner; public class Main2 { //并查集 public static void main(String[] args) { Scanner scan = new Scanner(System.in); while(scan.hasNext()) { int p = scan.nextInt(); //p人 int n = scan.nextInt(); //n个关系 scan.nextLine(); String input = scan.nextLine(); // String s = ""; HashSet<String> names = new HashSet<>(); String[] relations = input.split(" "); for (int i = 0; i < relations.length; i++) { names.add(relations[i]); } ArrayList<Node> nodes = new ArrayList<Node>();   Node node; //建好所有节点 for (String s2: names) { node = new Node(s2); nodes.add(node); } //遍历所有关系 for (int i = 0; i < relations.length; i+=2) { Node n1 = new Node(relations[i]); Node n2 = new Node(relations[i+1]); int i1 = nodes.indexOf(n1); int i2 = nodes.indexOf(n2); if(i1!=-1&&i2!=-1) { nodes.remove(n1); nodes.remove(n2); if(n1.parents.size()==0) n1.union(n2); else n2.union(n1); nodes.add(n1); } else if(i1!=-1) { //找i2的位置 for (Node no: nodes) { Node pa = no.getParent(n2); if(pa !=null) { nodes.remove(n1); pa.union(n1); break; } } } else if(i2!=-1) { for (Node no: nodes) { Node pa = no.getParent(n1); if(pa != null) { nodes.remove(n2); pa.union(n2); break; } } } } if(nodes.size() >1) { System.out.println("DISCONNECTED");  } else { System.out.println(nodes.get(0).height()); } } scan.close(); } } class Node { ArrayList<Node> parents = new ArrayList<>(); public String name; Node(String s) { name = s; } void union(Node parent) { for(Node n: parents) { if(n.name.equals(parent.name)) return; } parents.add(parent); } Node getParent(Node node) { if(parents.size() == 0) { if(this.name.equals(node.name)) return this; else return null; } else { for (Node n: parents) { return n.getParent(node); } } return null; } int height() { if(this.parents.size() ==0) { return 0; } int max = 0; for (Node no: parents) { max = Math.max(no.height()+1, max); } return max; } @Override public boolean equals(Object obj) { // TODO Auto-generated method stub return ((Node)obj).name.equals(this.name); } } /** **  4 2    A B C D */
点赞 回复
分享
发布于 2017-09-14 12:33
C++一个都没A。感觉是没戏了。
点赞 回复
分享
发布于 2017-09-14 13:22
秋招专场
校招火热招聘中
官网直投
看了楼上上的觉得去哪儿的题好可怕
点赞 回复
分享
发布于 2017-09-15 09:16

相关推荐

点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务