https://codeforces.com/contest/1205/problem/B
B. Shortest Cycle
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given nn integer numbers a1,a2,…,ana1,a2,…,an. Consider graph on nn nodes, in which nodes ii, jj (i≠ji≠j) are connected if and only if, aiaiAND aj≠0aj≠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)(1≤n≤105) — number of numbers.
The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10180≤ai≤1018).
Output
If the graph doesn't have any cycles, output −1−1. Else output the length of the shortest cycle.
Examples
input
Copy
4
3 6 28 9
output
Copy
4
input
Copy
5
5 12 9 16 48
output
Copy
3
input
Copy
4
1 2 4 8
output
Copy
-1
Note
In the first example, the shortest cycle is (9,3,6,28)(9,3,6,28).
In the second example, the shortest cycle is (5,12,9)(5,12,9).
The graph has no cycles in the third example.
当不为0的数,大于63*2时,所有数的二进制一定会有某一位出现1的次数>=3个,所以一定有环。用floyd求最小环,时间复杂度O(n^3).
floyd也是一种动态规划思想:
a,b两点考虑1——k点为中间点的最短距离 =
a,b两点考虑1——k-1点为中间点的最短距离 与
a,k两点考虑1——k-1点为中间点的最短距离 + b,k两点考虑1——k-1点为中间点的最短距离
的最大值。
import java.util.*;
import java.io.*;
public class Main {
public static void main(String args[]) {new Main().run();}
FastReader in = new FastReader();
PrintWriter out = new PrintWriter(System.out);
void run(){
out.println(work());
out.flush();
}
long mod=998244353L;
int ret=99999999;
int[][] graph,dis;
int work() {
int n=in.nextInt();
List<Long> list=new ArrayList<>();
for(int i=0,cnt=0;i<n;i++){
long a=in.nextLong();
if(a>0){
cnt++;
list.add(a);
}
if(cnt>129) return 3;
}
int size=list.size();
graph=new int[size][size];
dis=new int[size][size];
for(int i=0;i<size;i++){
for(int j=i+1;j<size;j++) {
if((list.get(i)&list.get(j))!=0) {
graph[i][j]=1;
graph[j][i]=1;
dis[i][j]=1;
dis[j][i]=1;
}else {
graph[i][j]=99999999;
graph[j][i]=99999999;
dis[i][j]=99999999;
dis[j][i]=99999999;
}
}
}
for(int k=0;k<size-1;k++) {
for(int i=0;i<size;i++) {
for(int j=0;j<size;j++) {
dis[i][j]=Math.min(dis[i][j],dis[i][k]+dis[k][j]);
if(i!=j&&i<k+1&&j<k+1) {
ret=Math.min(ret,dis[i][j]+graph[i][k+1]+graph[j][k+1]);
}
}
}
}
return ret==99999999?-1:ret;
}
}
class FastReader
{
BufferedReader br;
StringTokenizer st;
public FastReader()
{
br=new BufferedReader(new InputStreamReader(System.in));
}
public String next()
{
if(st==null || !st.hasMoreElements())
{
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt()
{
return Integer.parseInt(next());
}
public long nextLong()
{
return Long.parseLong(next());
}
}
参考:
https://www.cnblogs.com/wangyuliang/p/9216365.html
https://www.cnblogs.com/FuTaimeng/p/5610406.html
https://wenku.baidu.com/view/d334c6d73186bceb19e8bbf6.html