为了更好的阅读体检,可以查看我的算法学习博客报文回路
输入描述
第一行抓到的报文数量,后续C行依次输入设备节点D1和D2,表示从D1到D2发送了单向的报文,D1和D2用空格隔开
输出描述
组播
通路是否“正常”,正常输出True, 异常输出False。
样例
输入
5 1 2 2 3 3 2 1 2 2 1
输出
True
说明
无
输入
3 1 3 3 2 2 3
输出
True
说明
无
Java算法源码
import java.util.HashMap; import java.util.HashSet; import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); HashMap<Integer, HashSet<Integer>> trans = new HashMap<>(); for (int i = 0; i < n; i++) { int send = sc.nextInt(); int receive = sc.nextInt(); trans.putIfAbsent(send, new HashSet<>()); trans.putIfAbsent(receive, new HashSet<>()); trans.get(send).add(receive); } System.out.println(getResult(trans)); } public static String getResult(HashMap<Integer, HashSet<Integer>> trans) { for (Integer send : trans.keySet()) { for (Integer receive : trans.get(send)) { if (!trans.get(receive).contains(send)) { return "False"; } } } return "True"; } }
JS算法源码
/* JavaScript Node ACM模式 控制台输入获取 */ const readline = require("readline"); const rl = readline.createInterface({ input: process.stdin, output: process.stdout, }); const lines = []; let n; rl.on("line", (line) => { lines.push(line); if (lines.length === 1) { n = lines[0] - 0; } if (n && lines.length == n + 1) { lines.shift(); const trans = {}; lines .map((line) => line.split(" ")) .forEach((arr) => { const [send, receive] = arr; if (!trans[send]) trans[send] = new Set(); if (!trans[receive]) trans[receive] = new Set(); trans[send].add(receive); }); console.log(getResult(trans)); lines.length = 0; } }); function getResult(trans) { for (let send in trans) { for (let receive of trans[send]) { if (!trans[receive].has(send)) return "False"; } } return "True"; }
Python算法源码
# 输入获取 n = int(input()) arr = [input().split() for _ in range(n)] trans = {} for send, receive in arr: if trans.get(send) is None: trans[send] = set() if trans.get(receive) is None: trans[receive] = set() trans[send].add(receive) # 算法入口 def getResult(): for s in trans: for c in trans[s]: if s not in trans[c]: return "False" return "True" # 算法调用 print(getResult())