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 @@ -168,6 +168,72 @@ int main() {
168168
169169### Javascript
170170
171+ ``` java
172+ const r1 = require(' readline' ). createInterface({ input: process. stdin });
173+ // 创建readline接口
174+ let iter = r1[Symbol . asyncIterator]();
175+ // 创建异步迭代器
176+ const readline = async () = > (await iter. next()). value;
177+
178+
179+ let N , M // 节点数和边数
180+ let source, destination // 起点 终点
181+ let father = [] // 并查集
182+
183+
184+ // 并查集初始化
185+ const init = () = > {
186+ for (let i = 1 ; i <= N ; i++ ) father[i] = i;
187+ }
188+
189+ // 并查集里寻根的过程
190+ const find = (u) = > {
191+ return u == father[u] ? u : father[u] = find(father[u])
192+ }
193+
194+ // 将v->u 这条边加入并查集
195+ const join = (u, v) = > {
196+ u = find(u)
197+ v = find(v)
198+ if (u == v) return // 如果发现根相同,则说明在一个集合,不用两个节点相连直接返回
199+ father[v] = u
200+ }
201+
202+ // 判断 u 和 v是否找到同一个根
203+ const isSame = (u, v) = > {
204+ u = find(u)
205+ v = find(v)
206+ return u == v
207+ }
208+
209+
210+ (async function () {
211+ // 读取第一行输入
212+ let line = await readline();
213+ [N , M ] = line. split(' ' ). map(Number );
214+
215+ // 初始化并查集
216+ father = new Array (N )
217+ init()
218+
219+ // 读取边信息, 加入并查集
220+ for (let i = 0 ; i < M ; i++ ) {
221+ line = await readline()
222+ line = line. split(' ' ). map(Number )
223+ join(line[0 ], line[1 ])
224+ }
225+
226+ // 读取起点和终点
227+ line = await readline(); // JS注意这里的冒号
228+ [source, destination] = line. split(' ' ). map(Number )
229+
230+ if (isSame(source, destination)) return console. log(1 );
231+ console. log(0 );
232+ })()
233+ ```
234+
235+
236+
171237### TypeScript
172238
173239### PhP
You can’t perform that action at this time.
0 commit comments