---
id: 1683
lang: en
translation_of: index.md
source_sha256: c1c45bedaeb9a2085d704af07a7bb1d91bf7099b9c1b792529c303bc9d55087c
title: "[Codeforces 1206D] Shortest Path — Solution"
description: "The intended solution shrinks the problem by settling some answers in advance as special cases, then finds the minimum cycle with Floyd."
tags: ["OI","Graph Theory","Shortest Path","Floyd","Minimum Cycle"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "基底点 rendered literally as “base points”; 某一个位上 as “on some bit”."
---

## Main Idea

At first I thought it was about picking $\log n$ base points and then doing stuff on the bidirectional edges, but in the end I found that finding the minimum cycle in the graph has a very high complexity. So, <span class="slang" data-zh="GG" data-gloss="Gamer shorthand for “good game”, typed when conceding a match. Here: it is over, I am done for.">GG</span>.

The intended solution considers shrinking the size of the problem: that is, handling some answers as special cases in advance. For example, if more than three points are connected on some bit, then the size of the cycle can be determined to be $3$, which is the smallest possible. Consider that once there are more than $3 \times 60$ of them, we can directly conclude that the answer is $3$.

Now consider the remaining cases. At this point, $n$ has already shrunk a lot, so we build the graph by brute force and run Floyd for the minimum cycle, and that's it.

<!--more-->

## Code

```cpp
// CF1206D.cpp
#include <bits/stdc++.h>
#define ll long long

using namespace std;

const int MAX_N = 1e5 + 200;

ll n, cnt[MAX_N], matrix[150][150], dist[150][150], tot, ai[MAX_N];

int main()
{
    scanf("%d", &n);
    for (ll i = 1, tmp; i <= n; i++)
    {
        scanf("%lld", &tmp);
        if (tmp)
            ai[++tot] = tmp;
    }
    if (tot >= 150)
        puts("3"), exit(0);
    for (int i = 1; i <= tot; i++)
        for (int j = 1; j <= tot; j++)
            if ((ai[i] & ai[j]) != 0 && i != j)
                matrix[i][j] = dist[i][j] = 1;
            else
                matrix[i][j] = dist[i][j] = 1e9;

    // graph contructed;
    ll ans = 1e9;
    for (int k = 1; k <= tot; k++)
    {
        for (int i = 1; i <= tot; i++)
            for (int j = i + 1; j <= tot; j++)
                ans = min(ans, dist[i][j] + matrix[i][k] + matrix[k][j]);
        for (int i = 1; i <= tot; i++)
            for (int j = 1; j <= tot; j++)
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]);
    }
    if (ans >= 1e9)
        puts("-1");
    else
        printf("%d", ans);
    return 0;
}
```
