Codeforces 1205B Shortest Cycle

B. Shortest Cycle

time limit per test: 1 second
memory limit per test: 256 megabytes
input: standard input
output: standard 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, a i a_i ai AND a j ≠ 0 a_j≠0 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 ≤ 1 0 5 1≤n≤10^5 1n105) — number of numbers.
The second line contains n integer numbers a 1 , a 2 , … , a n a_1,a_2,…,a_n a1,a2,,an ( 0 ≤ a i ≤ 1 0 18 0≤a_i≤10^{18} 0ai1018).

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.

需要注意的是,ans=-1或者ans>=3
若n>128,则直接输出3
限制了n的大小,实际上相当了解放了复杂度!
直接Floyd算法走起!

#include <iostream>
#include <cstdio>
#define N 135
using namespace std;
typedef long long ll;

ll n, cnt, mn=1e9, a[N], d[N][N], e[N][N];
int main() {
	ll i, j, k, t;
	cin>>n;
	for(i=0; i<n; i++) {
		scanf("%I64d", &t);
		if(t) {
			a[cnt++] = t;
			if(cnt>128) break;
		}
	}
	if(i<n) {
		puts("3");
		return 0;
	}
	for(i=0; i<cnt; i++)
		for(j=0; j<cnt; j++) {
			if(i!=j && a[i]&a[j]) d[i][j] = e[i][j] = 1;
			else d[i][j] = e[i][j] = 1e9;
		}
	for(k=0; k<cnt; k++) {
		
		for(i=0; i<k; i++) {
			for(j=i+1; j<k; j++) {
				mn = min(mn, e[i][k] + e[k][j] + d[i][j]);
			}
		} 

		for(i=0; i<cnt; i++) {
			for(j=0; j<cnt; j++) {
				d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
			}
		}

	}
	cout<<(mn<1e9 ? mn : -1);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值