File tree Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Expand file tree Collapse file tree 1 file changed +66
-0
lines changed Original file line number Diff line number Diff line change @@ -223,6 +223,72 @@ class DisJoint{
223223
224224### Javascript
225225
226+ ``` java
227+ const r1 = require(' readline' ). createInterface({ input: process. stdin });
228+ // 创建readline接口
229+ let iter = r1[Symbol . asyncIterator]();
230+ // 创建异步迭代器
231+ const readline = async () = > (await iter. next()). value;
232+
233+
234+ let N , M // 节点数和边数
235+ let source, destination // 起点 终点
236+ let father = [] // 并查集
237+
238+
239+ // 并查集初始化
240+ const init = () = > {
241+ for (let i = 1 ; i <= N ; i++ ) father[i] = i;
242+ }
243+
244+ // 并查集里寻根的过程
245+ const find = (u) = > {
246+ return u == father[u] ? u : father[u] = find(father[u])
247+ }
248+
249+ // 将v->u 这条边加入并查集
250+ const join = (u, v) = > {
251+ u = find(u)
252+ v = find(v)
253+ if (u == v) return // 如果发现根相同,则说明在一个集合,不用两个节点相连直接返回
254+ father[v] = u
255+ }
256+
257+ // 判断 u 和 v是否找到同一个根
258+ const isSame = (u, v) = > {
259+ u = find(u)
260+ v = find(v)
261+ return u == v
262+ }
263+
264+
265+ (async function () {
266+ // 读取第一行输入
267+ let line = await readline();
268+ [N , M ] = line. split(' ' ). map(Number );
269+
270+ // 初始化并查集
271+ father = new Array (N )
272+ init()
273+
274+ // 读取边信息, 加入并查集
275+ for (let i = 0 ; i < M ; i++ ) {
276+ line = await readline()
277+ line = line. split(' ' ). map(Number )
278+ join(line[0 ], line[1 ])
279+ }
280+
281+ // 读取起点和终点
282+ line = await readline(); // JS注意这里的冒号
283+ [source, destination] = line. split(' ' ). map(Number )
284+
285+ if (isSame(source, destination)) return console. log(1 );
286+ console. log(0 );
287+ })()
288+ ```
289+
290+
291+
226292### TypeScript
227293
228294### PhP
You can’t perform that action at this time.
0 commit comments