最小环 floyd java_干货|Floyd求最小环(CF Shortest Cycle)

本文通过实例分析和代码讲解介绍了使用Floyd算法求解图中最小环的问题,涉及位运算和图论知识。当节点数量超过2*64时,直接输出3作为最短环长度。代码实现中避免了memset初始化导致的问题。
摘要由CSDN通过智能技术生成

作者:Water_Fox

来源:牛客网

You are given nn integer numbers a1,a2,…,ana1,a2,…,an. Consider graph on nn nodes, in which nodes i, j (i≠j) are connected if and only if, aiai AND aj≠0, where AND denotes the bitwise AND operation.

Find the length of the shortest cycle in this graph or determine that it doesn't have cycles at all.

Input

The first line contains one integer nn (1≤n≤105) — number of numbers.

The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤1018).

Output

If the graph doesn't have any cycles, output −1. Else output the length of the shortest cycle.

Examples

input

4

3 6 28 9

output

4

input

5

5 12 9 16 48

output

3

input

4

1 2 4 8

output

-1

Note

In the first example, the shortest cy

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Floyd算法找到无向图的最小,可以先使用Floyd算法出图中任意两个顶点之间的最短路径,然后再遍历所有的三角形(三个顶点组成的)找到最小。 以下是一个使用Python实现Floyd算法解无向图最小的示例: ```python INF = float('inf') def floyd(graph): n = len(graph) dist = [[INF] * n for _ in range(n)] # 初始化距离矩阵 next_vertex = [[-1] * n for _ in range(n)] # 记录最短路径上的下一个顶点 # 初始化距离矩阵和下一个顶点矩阵 for i in range(n): for j in range(n): if i == j: dist[i][j] = 0 elif graph[i][j] != 0: dist[i][j] = graph[i][j] next_vertex[i][j] = j # 使用Floyd算法计算最短路径和下一个顶点 for k in range(n): for i in range(n): for j in range(n): if dist[i][j] > dist[i][k] + dist[k][j]: dist[i][j] = dist[i][k] + dist[k][j] next_vertex[i][j] = next_vertex[i][k] return dist, next_vertex def find_min_cycle(graph): n = len(graph) min_cycle_length = INF dist, next_vertex = floyd(graph) # 遍历所有三角形,找到最小 for u in range(n): for v in range(u+1, n): for w in range(v+1, n): if graph[u][v] != 0 and graph[v][w] != 0 and graph[w][u] != 0: cycle_length = dist[u][v] + dist[v][w] + dist[w][u] - 2 * (graph[u][v] + graph[v][w] + graph[w][u]) if cycle_length < min_cycle_length: min_cycle_length = cycle_length return min_cycle_length ``` 使用上述代码,可以通过传入一个邻接矩阵表示的无向图,来计算出最小的长度。其中,`graph`是一个二维列表,表示图的邻接矩阵,如果两个顶点之间没有边,则对应位置的值为0。 注意,这里的最小指的是由三个顶点组成的,并且每个顶点都与相邻的两个顶点相连。如果图中不存在这样的,则返回无穷大(INF)。 希望能够帮助到你!如有更多问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值