D. Shortest Cycle
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

You are given 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 (1≤n≤105) — number of numbers.

The second line contains 0≤ai≤1018).

Output

If the graph doesn't have any cycles, output −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).

In the second example, the shortest cycle is (5,12,9).

The graph has no cycles in the third example.

#include<iostream>
#include<cstdio>
#include<cstring>
#define maxn 100010
using namespace std;
int n,map[210][210],dis[210][210],ans;
long long a[maxn];
int main(){
    scanf("%d",&n);
    int cnt=0;
    for(int i=1;i<=n;i++){
        long long x;
        scanf("%lld",&x);
        if(x!=0)a[++cnt]=x;
    }
    n=cnt;
    if(n>=200){
        puts("3");
        return 0;
    }
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++){
            if(i==j)continue;
            dis[i][j]=map[i][j]=100000000;
        }
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++){
            if(i==j)continue;
            if((a[i]&a[j])!=0)
                map[i][j]=map[j][i]=dis[i][j]=dis[j][i]=1;
        }
    ans=0x7fffffff;
    for(int k=1;k<=n;k++){
        for(int i=1;i<k;i++){
            for(int j=i+1;j<k;j++){
                ans=min(dis[i][j]+map[i][k]+map[k][j],ans);
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]);
            }
        }
    }
    if(ans>n){
        puts("-1");
        return 0;
    }
    else printf("%d\n",ans);
    return 0;
}

 

相关文章: