关注
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
相关推荐
牛客热帖
正在热议
# 25届秋招总结 #
343147次浏览 3283人参与
# 我的实习求职记录 #
6078982次浏览 83620人参与
# 北方华创开奖 #
39232次浏览 406人参与
# 地方国企笔面经互助 #
4873次浏览 13人参与
# 职场吐槽大会 #
89820次浏览 740人参与
# 选完offer后,你后悔学本专业吗 #
22507次浏览 161人参与
# 百度开奖 #
193643次浏览 1236人参与
# 运营商笔面经互助 #
92025次浏览 1330人参与
# ai智能作图 #
1462次浏览 36人参与
# 如果有时光机,你最想去到哪个年纪? #
23587次浏览 475人参与
# 海康威视求职进展汇总 #
401753次浏览 3414人参与
# 软件开发2024笔面经 #
2324338次浏览 48209人参与
# 风评不好的公司,你会去吗? #
20540次浏览 94人参与
# 国企还是互联网,你怎么选? #
89811次浏览 697人参与
# 如何一边实习一边秋招 #
998771次浏览 12683人参与
# 腾讯求职进展汇总 #
197823次浏览 1650人参与
# 银行笔面经互助 #
84334次浏览 891人参与
# 第一份工作应该选择高薪还是大平台 #
88747次浏览 590人参与
# bilibili求职进展汇总 #
33746次浏览 361人参与
# 许愿池 #
215297次浏览 2536人参与
# 上班苦还是上学苦呢? #
78581次浏览 725人参与
# 国央企薪资爆料 #
13332次浏览 98人参与