Skip to content

Commit 1609759

Browse files
Merge pull request youngyangyang04#2680 from nineninee/km0108
添加 卡码网0108.冗余连接 JS版
2 parents 6121de1 + 006fb93 commit 1609759

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

Diff for: problems/kamacoder/0108.冗余连接.md

+64
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,70 @@ int main() {
141141
142142
### Javascript
143143
144+
```javascript
145+
const r1 = require('readline').createInterface({ input: process.stdin });
146+
// 创建readline接口
147+
let iter = r1[Symbol.asyncIterator]();
148+
// 创建异步迭代器
149+
const readline = async () => (await iter.next()).value;
150+
151+
152+
let N // 节点数和边数
153+
let father = [] // 并查集
154+
155+
156+
// 并查集初始化
157+
const init = () => {
158+
for (let i = 1; i <= N; i++) father[i] = i;
159+
}
160+
161+
// 并查集里寻根的过程
162+
const find = (u) => {
163+
return u == father[u] ? u : father[u] = find(father[u])
164+
}
165+
166+
// 将v->u 这条边加入并查集
167+
const join = (u, v) => {
168+
u = find(u)
169+
v = find(v)
170+
if (u == v) return // 如果发现根相同,则说明在一个集合,不用两个节点相连直接返回
171+
father[v] = u
172+
}
173+
174+
// 判断 u 和 v是否找到同一个根
175+
const isSame = (u, v) => {
176+
u = find(u)
177+
v = find(v)
178+
return u == v
179+
}
180+
181+
182+
(async function () {
183+
// 读取第一行输入
184+
let line = await readline();
185+
N = Number(line);
186+
187+
// 初始化并查集
188+
father = new Array(N)
189+
init()
190+
191+
// 读取边信息, 加入并查集
192+
for (let i = 0; i < N; i++) {
193+
line = await readline()
194+
line = line.split(' ').map(Number)
195+
196+
if (!isSame(line[0], line[1])) {
197+
join(line[0], line[1])
198+
}else{
199+
console.log(line[0], line[1]);
200+
break
201+
}
202+
}
203+
})()
204+
```
205+
206+
207+
144208
### TypeScript
145209

146210
### PhP

0 commit comments

Comments
 (0)