关注
public class NIOTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Node> res = new ArrayList<>();
HashMap<String, Node> relation = new HashMap<>();
boolean flag = true;
while (sc.hasNext()) {
String str = sc.nextLine();
parse(str, relation);
if (str.charAt(str.length() - 1) != ',')
break;
}
while (!relation.isEmpty() && flag == true) {
flag = false;
Node node = null;
for (Map.Entry<String, Node> entry : relation.entrySet()) {
Node cur = entry.getValue();
if (cur.degree == 0) {
node = cur;
break;
}
}
if (node != null) {
for (Node temp : node.relation) {
temp.degree--;
}
res.add(node);
relation.remove(node.name);
flag = true;
}
}
for (Map.Entry<String, Node> entry : relation.entrySet()) {
res.add(entry.getValue());
}
Collections.sort(res, new Comparator<Node>() {
public int compare(Node a, Node b) {
return a.name.compareTo(b.name);
}
});
for (int i = 0; i < res.size() - 1; i++) {
boolean b = res.get(i).degree == 0 ? false : true;
System.out.println("{" + res.get(i).name + ", " + b + "},");
}
boolean b = res.get(res.size() - 1).degree == 0 ? false : true;
System.out.println("{" + res.get(res.size() - 1).name + ", " + b + "}");
}
public static void parse(String str, HashMap<String, Node> relation) {
String[] strs = str.split(",");
String A = strs[0].substring(1, strs[0].length());
String B = strs[1].substring(1, strs[1].length() - 1);
Node nodeA = relation.get(A);
if (nodeA == null) {
nodeA = new Node(A, null, 1);
relation.put(A, nodeA);
} else {
nodeA.degree++;
}
Node nodeB = relation.get(B);
if (nodeB == null) {
nodeB = new Node(B, nodeA, 0);
relation.put(B, nodeB);
} else {
nodeB.relation.add(nodeA);
}
}
public static class Node {
public String name;
public LinkedList<Node> relation = new LinkedList<>();
public int degree;
public Node (String name, Node relation, int degree) {
this.name = name;
if (relation != null)this.relation.add(relation);
this.degree = degree;
}
}
}
查看原帖
点赞 2
相关推荐
点赞 评论 收藏
分享

点赞 评论 收藏
分享
牛客热帖
更多
正在热议
更多
# 实习,不懂就问 #
4812次浏览 75人参与
# 小米提前批笔试难吗 #
34165次浏览 358人参与
# 现代汽车前瞻技术研发急速编程挑战赛 #
14571次浏览 146人参与
# 26届校招投递进展 #
32372次浏览 248人参与
# 央国企投递记录 #
88275次浏览 1362人参与
# 为了找工作你花了哪些钱? #
28496次浏览 275人参与
# 神州信息工作体验 #
11692次浏览 57人参与
# 校招第一份工作你干了多久? #
86246次浏览 395人参与
# 来聊聊你目前的求职进展 #
634423次浏览 6747人参与
# 考公还是考研,你怎么选? #
27821次浏览 140人参与
# 小米硬件提前批进度交流 #
168217次浏览 1523人参与
# 外包能不能当跳板? #
34570次浏览 221人参与
# 你觉得专业和学校哪个对薪资影响最大 #
61420次浏览 490人参与
# 设计人的面试记录 #
123594次浏览 1341人参与
# 打工人的精神状态 #
49968次浏览 866人参与
# 硬件人你反向读研了吗 #
42574次浏览 637人参与
# 如果中了500万,你会离职吗? #
84537次浏览 652人参与
# 你今年的保底offer是哪家 #
118546次浏览 538人参与
# 大疆的机械笔试比去年难吗 #
72974次浏览 619人参与
# 怎么评价今年的华为 #
129130次浏览 568人参与
# 硬件人秋招的第一个offer #
78026次浏览 1149人参与