codefores741A Arpa's loud Owf and Mehrdad's evil plan(图找环)
生活随笔
收集整理的這篇文章主要介紹了
codefores741A Arpa's loud Owf and Mehrdad's evil plan(图找环)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題意:
對于給定的一個數(shù)列a[n],如果現(xiàn)在點i,那么下一個點就在a[i],現(xiàn)在問給定n個點,找到一個最小的t,使得對于從任意一個點x出發(fā),經(jīng)過t次之后,到達(dá)的點y, 使得點y經(jīng)過t次之后會回到點x。
要點:
一看就是圖找環(huán),找到所有獨立的環(huán)對應(yīng)的節(jié)點數(shù),對所有節(jié)點數(shù)求最小公倍數(shù)就是結(jié)果。有個地方要注意就是,當(dāng)節(jié)點數(shù)是偶數(shù)時,比如1->2->3->4->1,這種情況要將節(jié)點數(shù)/2計算,因為比如1到達(dá)3要2次,3到達(dá)1也是兩次,肯定比從1繞一圈再到1要小,奇數(shù)沒有辦法。
#include<cstdio> #include<iostream> #include<cstring> #include<string> #include<map> #include<queue> #include<vector> #include<algorithm> using namespace std; typedef long long ll; const int N = 105; int a[N], vis[N]; ll b[N];int dfs(int u, int s, int l)//有向圖找環(huán) {if (u == s) {l = l + 1;return l;}if (vis[u] && u != s) {return -1;}vis[u] = 1;if (a[u] == s)return dfs(a[u], s, l);elsereturn dfs(a[u], s, l + 1); } ll gcd(ll a, ll b) {if (b == 0) return a;return gcd(b, a%b); }int main() {int n;scanf("%d", &n);for (int i = 1; i <= n; i++)scanf("%d", &a[i]);memset(vis, 0, sizeof(vis));int cnt = 0;bool flag = true;for (int i = 1; i <= n; i++){if (vis[i])continue;int temp = dfs(a[i], i, 1);if (temp != -1){if (temp % 2 == 0)temp /= 2;b[cnt++] = temp;}else{flag = false;break;}}if (!flag)printf("-1\n");else{ll lcm, c = b[0], e;for (int i = 0; i < cnt; i++)//計算lcm{e = gcd(c, b[i]);lcm = c*b[i] / e;c = lcm;}printf("%I64d\n", lcm);}return 0; }轉(zhuǎn)載于:https://www.cnblogs.com/seasonal/p/10343651.html
總結(jié)
以上是生活随笔為你收集整理的codefores741A Arpa's loud Owf and Mehrdad's evil plan(图找环)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: MySQL查询数据操作(DQL)
- 下一篇: DNS设定(二)