Shortest Cycle

You are given n integer numbers a1,a2,…,an. Consider graph on n nodes, in which nodes i, j (i≠j) are connected if and only if, ai 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 n (1≤n≤105) — number of numbers.

The second line contains n integer numbers a1,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 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.

题目大意:两个数按位与后值不为0,则两数之间有一条边,求最小环

思路:long long类型二进制下最多63位数,当大于 0 的数大于 2 * 63 个时,至少有 3 个数同一位含 1,此时最小环值为 3;大于 0 的 数 小于 2 * 63个时,floyd求最小环

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int inf = 1e7;
const int MAX_N=2e2 + 10;
const int MOD = 1e9 + 7;
int N;
ll a[(int)1e5 + 10];
int d[MAX_N][MAX_N], f[MAX_N][MAX_N];
int ans = inf, cnt = 0;
void floyd(){
    for(int k = 0; k < cnt; k++){
        for(int i = 0; i < k; i++){
            for(int j = i+1; j < k; j++){
                ans = min(ans, d[i][j] + f[i][k] + f[k][j]);
            }
        }
        for(int i = 0; i < cnt; i++){
            if(d[i][k] != inf){
                for(int j = 0; j < cnt; j++){
                    d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
                }
            }
        }
    }
}
void solve(){
    ll x;
    scanf("%d", &N);
    for(int i = 0; i < N; i++){
        scanf("%lld", &x);
        if(x != 0) a[cnt++] = x;
    }
    if(cnt > 126){
        printf("3\n");
    }else{
        for(int i = 0; i < cnt; i++){
            for(int j = i+1; j < cnt; j++){
                if((a[i] & a[j]) > 0) d[i][j] = d[j][i] = f[i][j] = f[j][i] = 1;
                else d[i][j] = d[j][i] = f[i][j] = f[j][i] = 1e7;
            }
        }
        floyd();
        if(ans != inf){
            printf("%d\n", ans);
        }else{
            printf("-1\n");
        }
    }
}
int main(){
    int TCASE = 1;
//    scanf("%d", &TCASE);
    while(TCASE--){
        solve();
    }
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值