This commit is contained in:
programmercarl
2024-09-14 11:22:01 +08:00
parent 572e6e17d5
commit 4651291226
6 changed files with 319 additions and 50 deletions

BIN
problems/kamacoder/.DS_Store vendored Normal file

Binary file not shown.

View File

@@ -7,9 +7,15 @@
题目描述
树可以看成是一个图(拥有 n 个节点和 n - 1 条边的连通无环无向图)。
有一个图,它是一棵树,他是拥有 n 个节点节点编号1到n和 n - 1 条边的连通无环无向图(其实就是一个线形图),如图:
现给定一个拥有 n 个节点(节点编号从 1 到 n和 n 条边的连通无向图,请找出一条可以删除的边,删除后图可以变成一棵树。
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240905163122.png)
现在在这棵树上的基础上添加一条边依然是n个节点但有n条边使这个图变成了有环图如图
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240905164721.png)
先请你找出冗余边,删除后,使该图可以重新变成一棵树。
输入描述
@@ -60,12 +66,11 @@
那么我们就可以从前向后遍历每一条边(因为优先让前面的边连上),边的两个节点如果不在同一个集合,就加入集合(即:同一个根节点)。
如图所示:
如图所示节点A 和节点 B 不在同一个集合,那么就可以将两个 节点连在一起。
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20230604104720.png)
节点A 和节点 B 不在同一个集合,那么就可以将两个 节点连在一起。
如果边的两个节点已经出现在同一个集合里,说明着边的两个节点已经连在一起了,再加入这条边一定就出现环了。
如图所示:
@@ -127,6 +132,44 @@ int main() {
可以看出,主函数的代码很少,就判断一下边的两个节点在不在同一个集合就可以了。
## 拓展
题目要求 “请删除标准输入中最后出现的那条边” ,不少录友疑惑,这代码分明是遇到在同一个根的两个节点立刻就返回了,怎么就求出 最后出现的那条边 了呢。
有这种疑惑的录友是 认为发现一条冗余边后,后面还可能会有一条冗余边。
其实并不会。
题目是在 树的基础上 添加一条边,所以冗余边仅仅是一条。
到这一条可能靠前出现,可能靠后出现。
例如,题目输入示例:
输入示例
```
3
1 2
2 3
1 3
```
图:
![](https://code-thinking-1253855093.file.myqcloud.com/pics/20240527110320.png)
输出示例
1 3
当我们从前向后遍历,优先让前面的边连上,最后判断冗余边就是 1 3。
如果我们从后向前便利,优先让后面的边连上,最后判断的冗余边就是 1 2。
题目要求“请删除标准输入中最后出现的那条边”,所以 1 3 这条边才是我们要求的。
## 其他语言版本

View File

@@ -337,6 +337,38 @@ IDA * 算法 对这一空间增长问题进行了优化,关于 IDA * 算法,
### Python
```Python
import heapq
n = int(input())
moves = [(1, 2), (2, 1), (-1, 2), (2, -1), (1, -2), (-2, 1), (-1, -2), (-2, -1)]
def distance(a, b):
return ((a[0] - b[0]) ** 2 + (a[1] - b[1]) ** 2) ** 0.5
def bfs(start, end):
q = [(distance(start, end), start)]
step = {start: 0}
while q:
d, cur = heapq.heappop(q)
if cur == end:
return step[cur]
for move in moves:
new = (move[0] + cur[0], move[1] + cur[1])
if 1 <= new[0] <= 1000 and 1 <= new[1] <= 1000:
step_new = step[cur] + 1
if step_new < step.get(new, float('inf')):
step[new] = step_new
heapq.heappush(q, (distance(new, end) + step_new, new))
return False
for _ in range(n):
a1, a2, b1, b2 = map(int, input().split())
print(bfs((a1, a2), (b1, b2)))
```
### Go
### Rust