codeforces Round #383 (Div.2) C
来源:互联网 发布:数据库系统集成 编辑:程序博客网 时间:2024/04/29 20:19
题目 : Arpa’s loud Owf and Mehrdad’s evil plan
链接 : http://codeforces.com/contest/742/problem/C
题意: 给你 n 个点,每个点的出度都为 1 (这样就构成了很多环),求最小的 t 使得对于任意环中的任意两点 a , b 使得 a通过 t
步到 b , b 也通过 t步到 a。
分析:设环长为 k ,对于一个环,如果k是奇数 t = k , 如果是偶数 t = k/2.(画个图就很清楚了) 。 所以只需枚举每个环的 t , 求这些 t的 lcm就好了。
代码:
#include <iostream>#include <algorithm>#include <cstdio>#include <cstdlib>#include <cstring>using namespace std;const int N = 100+10;int book[N],fa[N],shu[N];int dfs(int x,int step);int gcd(int n,int m);int lcm(int n,int m);bool cmp(int a, int b){ return a > b;}int main(){ int n,i; while(~scanf("%d",&n)) { memset(book,0,sizeof(book)); memset(shu,0,sizeof(shu)); int sum = 0,cut = 0; for(i=1; i<=n; i++) { scanf("%d",&fa[i]); sum += fa[i]; } //如果有点的入度为零 , 则不符合题意(构不成环) if(sum != (n*n + n)/2) { printf("-1\n"); continue; } for(i=1; i<=n; i++) if(book[i] == 0) { int a = dfs(i,0); shu[++cut] = a%2 == 0? a/2 : a; } int ans = shu[1]; for(i=2; i<=cut; i++) ans = lcm(ans,shu[i]); printf("%d\n",ans); } return 0;}int gcd(int n,int m){ if(m == 0) return n; return gcd(m,n%m);}int lcm(int n,int m){ return n/gcd(n,m)*m;}int dfs(int x,int step){ if(book[x] == 1) return step; book[x] = 1; return dfs(fa[x],step+1);}
0 0
- codeforces Round #383 (Div.2) C
- 【codeforces】Codeforces Round #370 (Div. 2) C
- Codeforces Round #383 (Div. 2)
- Codeforces Round #383 (Div. 2)
- Codeforces Round #383 (Div. 2)
- Codeforces Round #383 (Div. 2)
- Codeforces Round #383 (Div. 2)
- Codeforces Round #383 (Div. 2) C(递归找环求最小公倍数)
- 【Codeforces Round #383 (Div. 2)】 (A,B,C)
- Codeforces Round #383 (Div. 2) B, C, D
- Codeforces Round #105 (Div. 2) C
- Codeforces Round 134 div 2 C题
- Codeforces Round #137 (Div. 2), problem: (C)
- Codeforces Round #153 (Div. 2) C题
- Codeforces Round #158 (Div. 2) C题
- Codeforces Round #162 (Div. 2) C
- Codeforces Round #166 (Div. 2) c. Secret
- Codeforces Round#170(Div 2)C
- 牛客:剑指offer:二叉树的深度(Java)
- Linux c==网络编程的理论知识-dns端口和IP地址的作用(29)
- 怎么挽救unrecognized selector异常——消息转发机制
- 深度学习在目标检测中的应用
- consul-template入门篇
- codeforces Round #383 (Div.2) C
- Linux—管理用户和用户组
- 29. 数据库结构优化
- Git更新远程仓库代码到本地 git fetch
- Caffe 计时功能
- JSP中用application统计访客总人数
- HTTPS那些事 用java实现HTTPS工作原理
- expdp/impdp使用浅析
- ionic2中文翻译文档