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;
}

注意

注意&和!=的优先级。

发布了24 篇原创文章 · 获赞 9 · 访问量 554

猜你喜欢

转载自blog.csdn.net/salty_fishman/article/details/103943844