Shortest Cycle//最小环//CF1205B//floyd

Shortest Cycle//最小环//CF1205B//floyd


题目

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.
链接://https://vjudge.net/contest/351234#problem/D
大意
两个数&运算后不为0即可连成边,求最小环。

思路

求最小环常用floyd,数据量过大,需要特殊处理。发现不为0个数大于128后,答案一定是3。小于128的再构造图,用floyd算法求出其最小环即可。floyd求最小环模板题。

代码

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>

using namespace std;
long long a[200000];
long long fl[150][150];
long long w[150][150];
const long long MAXN = 100000000000000000;

void buildn(int n){
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            if((a[i]&a[j])&&i!=j)
                fl[i][j]=w[i][j]=1;           //连边,初始化
            else
                fl[i][j]=w[i][j]=MAXN;
        }
    }
    return ;
}
long long floyd(int n){
    long long ans=MAXN;
    for(int k=1;k<=n;k++){
        for(int i=1;i<k;i++){
            for(int j=i+1;j<k;j++){
                ans = min(ans,fl[i][j]+w[i][k]+w[k][j]);   //floyd求最小环
            }
        }
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n;j++){
                fl[i][j]=min(fl[i][j],fl[i][k]+fl[k][j]);
            }
        }
    }
    return ans;
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++){
        cin>>a[i];
        if(a[i]==0){                           //去除其中的0
            n--;
            i--;
        }
    }
    if(n>130){                         //超过128个不为0的数,答案一定是3;
        cout<<"3"<<endl;
        return 0;
    }
    else{
        buildn(n);
        int ans=floyd(n);
        if(ans>n)
            cout<<"-1"<<endl;
        else
            cout<<ans<<endl;
    }
    return 0;
}

注意

注意&和!=的优先级。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值