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

你可能感兴趣的:(ACM训练)