fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. int const PMAX = 10000;
  6. int const NMAX = 10000;
  7. int A, B;
  8. int N, P;
  9. int colors[1 + NMAX];
  10. int moves[1 + PMAX];
  11.  
  12. int bfs() {
  13. queue<int> q;
  14. q.push(A);
  15. while(true) {
  16. int from = q.front();
  17. q.pop();
  18. if(from == B) {
  19. return moves[from];
  20. }
  21. for(int i = 1; i <= N; i++) {
  22. int to = (from * colors[i]) % P;
  23. if(moves[to] == 0 && to != A) {
  24. moves[to] = moves[from] + 1;
  25. q.push(to);
  26. }
  27. }
  28. }
  29. }
  30.  
  31. int main() {
  32. cin >> A >> B;
  33. cin >> N >> P;
  34. for(int i = 1; i <= N; i++) {
  35. cin >> colors[i];
  36. }
  37. cout << bfs();
  38. }
Success #stdin #stdout 0.01s 5284KB
stdin
3 30
3 100
2 5 7
stdout
2