Codeforces 1206D 思维+floyed求最小环
You are given nn integer numbers a1,a2,…,ana1,a2,…,an. Consider graph on nn nodes, in which nodes ii, jj (i≠ji≠j) are connected if and only if, aiaiAND aj≠0aj≠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.
The first line contains one integer nn (1≤n≤105)(1≤n≤105) — number of numbers.
The second line contains nn integer numbers a1,a2,…,ana1,a2,…,an (0≤ai≤10180≤ai≤1018).
If the graph doesn't have any cycles, output −1−1. Else output the length of the shortest cycle.
4 3 6 28 9
4
5 5 12 9 16 48
3
4 1 2 4 8
-1
In the first example, the shortest cycle is (9,3,6,28)(9,3,6,28).
In the second example, the shortest cycle is (5,12,9)(5,12,9).
The graph has no cycles in the third example.
#include<iostream> #include<cstdio> #include<cstring> #define maxn 100010 using namespace std; int n,map[210][210],dis[210][210],ans; long long a[maxn]; int main(){ scanf("%d",&n); int cnt=0; for(int i=1;i<=n;i++){ long long x; scanf("%lld",&x); if(x!=0)a[++cnt]=x; } n=cnt; if(n>=200){ puts("3"); return 0; } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ if(i==j)continue; dis[i][j]=map[i][j]=100000000; } for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ if(i==j)continue; if((a[i]&a[j])!=0) map[i][j]=map[j][i]=dis[i][j]=dis[j][i]=1; } ans=0x7fffffff; for(int k=1;k<=n;k++){ for(int i=1;i<k;i++){ for(int j=i+1;j<k;j++){ ans=min(dis[i][j]+map[i][k]+map[k][j],ans); } } for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ dis[i][j]=min(dis[i][j],dis[i][k]+dis[k][j]); } } } if(ans>n){ puts("-1"); return 0; } else printf("%d\n",ans); return 0; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话