fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const long max_n = 2e6;
  5.  
  6. bool check[max_n+1];
  7. queue< pair<long, long> > q;
  8.  
  9. void test(long x, long cnt)
  10. {
  11. if (!check[x])
  12. {
  13. check[x] = true;
  14. q.push({x, cnt});
  15. }
  16. }
  17.  
  18. long Loang(long n, long p, long a, long b, long r)
  19. {
  20. memset(check, false, sizeof check);
  21. int cnt = 0;
  22. q.push({n%p,cnt});
  23. check[n] = true;
  24.  
  25. while(!q.empty())
  26. {
  27. tie(n, cnt) = q.front(); q.pop();
  28. if (n==r) return cnt;
  29.  
  30. test((n+a)%p, cnt+1);
  31. test((n+b)%p, cnt+1);
  32. test((n+a+b)%p, cnt+1);
  33. }
  34.  
  35. return -1;
  36. }
  37.  
  38. int main()
  39. {
  40. // freopen("REPLACE.INP", "r", stdin);
  41. // freopen("REPLACE.OUT", "w", stdout);
  42. ios_base::sync_with_stdio(0);
  43. cin.tie(0); cout.tie(0);
  44.  
  45. long long n; long p, a, b, r; cin >> n >> p >> a >> b >> r;
  46.  
  47. cout << Loang(n%p,p,a,b,r);
  48.  
  49. return 0;
  50. }
  51.  
Success #stdin #stdout 0.01s 5596KB
stdin
20 16 3 4 5
stdout
3