Advertisement
Brick99

CCC01 stage 2 The Monkey Dance

May 14th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <utility>
  4. #include <algorithm>
  5.  
  6. using namespace std;
  7.  
  8. int broj_koraka(pair <int, int> A[], int n, int broj)
  9. {
  10.     int kor=0;
  11.  
  12.     int prov=broj;
  13.     while (kor<2000000000)
  14.     {
  15.         for (int i=0;i<n;i++)
  16.             if ( A[i].first == broj ) { broj=A[i].second; kor++; break; }
  17.  
  18.         if ( broj == prov ) return kor;
  19.     }
  20.  
  21.     return 0;
  22. }
  23.  
  24. unsigned long long nzd(unsigned long long a, unsigned long long b)
  25. {
  26.     if ( a == 0 ) return b;
  27.     return nzd(b%a,a);
  28. }
  29.  
  30. unsigned long long nzs(unsigned long long a, unsigned long long b) { return (a*b)/nzd(a,b); }
  31.  
  32. int main()
  33. {
  34.     int n;
  35.     cin>>n;
  36.  
  37.     while (n!=0)
  38.     {
  39.         pair <int, int> A[n];
  40.  
  41.         for (int i=0;i<n;i++) cin>>A[i].first>>A[i].second;
  42.  
  43.         vector <unsigned long long> broj;
  44.  
  45.         for (int i=1;i<=n;i++)
  46.         {
  47.             bool prov=false;
  48.             for (int j=0;j<n;j++)
  49.             if ( i == A[j].first ) {prov=true;break;}
  50.  
  51.             if ( prov )
  52.             {
  53.                 int a=broj_koraka(A,n,i);
  54.  
  55.                 if ( a != 0 ) broj.push_back(a);
  56.             }
  57.         }
  58.  
  59.         if ( broj.size() == 1 ) cout<<broj[0]<<endl;
  60.         else
  61.         {
  62.             unsigned long long a=nzs(broj[0],broj[1]);
  63.  
  64.             for (int i=2;i<broj.size();i++) a=nzs(a,broj[i]);
  65.  
  66.             cout<<a<<endl;
  67.         }
  68.         cin>>n;
  69.     }
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement