time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
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
inputCopy
4
3 6 28 9
outputCopy
4
inputCopy
5
5 12 9 16 48
outputCopy
3
inputCopy
4
1 2 4 8
outputCopy
-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.
题意: 有n个点,每个点有相应的值ai,对于ai&aj !=0,连接i,j(i!=j),查找图中的最小环。
思路: 对于每三个数来说,若他们的二进制的第i位都为1,那么这三个点相互连接,即可构成一个圆。同理,当第i位为1的数大于等于3个时,他们之间相互连接,即最小环长度均为3.
除此之外,对于第i位至多有2个节点,将他们离散化后连接起来,所以至多有64条边,128个节点,floyd最小环便可以过掉。
代码:
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int INF = (1<<29);
vector<ll>ve[70];
map<ll,int>mp;
int graph[200][200];
int dis[200][200];
int cnt;
void floyd()
{
int MinCost = INF;
for(int k=1;k<=cnt;k++){
for(int i=1;i<k;i++)
for(int j=i+1;j<k;j++){
if(dis[i][j]==INF||graph[i][k]==INF||graph[k][j]==INF) continue;
MinCost = min(MinCost,dis[i][j]+graph[i][k]+graph[k][j]);//跟新k点之前枚举ij求经过ijk的最小环
}
for(int i=1;i<=cnt;i++)
for(int j=1;j<=cnt;j++)
dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]); //跟新k点
}
if(MinCost==INF)puts("-1");
else printf("%d\n",MinCost);
}
void init()
{
for(int i = 0; i <= 150; ++i){
for(int j = 0; j<= 150; ++j){
graph[i][j] = graph[j][i] = INF;
dis[i][j] = dis[j][i] = INF;
}
}
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 0; i < n; ++i){
ll x,cnt = 0; scanf("%lld",&x);
ll t = x;
while(t){
if(t&1) ve[cnt].push_back(x);
t /= 2;
cnt++;
}
}
init();
int flag = 0;
for(int i = 0; i <= 64; ++i){
int l = ve[i].size();
if(l == 0) continue;
else if(l == 1){
if(!mp[ve[i][0]]) mp[ve[i][0]] = ++cnt;
}
else if(l == 2){
ll x = ve[i][0], y = ve[i][1];
if(!mp[x]) mp[x] = ++cnt;
if(!mp[y]) mp[y] = ++cnt;
graph[mp[x]][mp[y]] = graph[mp[y]][mp[x]] = 1;
dis[mp[x]][mp[y]] = dis[mp[y]][mp[x]] = 1;
}
else {flag = 1; break;}
}
if(flag) cout<<3<<endl;
else floyd();
return 0;
}