Advertisement
Guest User

Untitled

a guest
Jun 29th, 2017
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.96 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3. #include<cstring>
  4. #include<queue>
  5. #include<algorithm>
  6. using namespace std;
  7. int dist[10000];
  8. void bfs(string a, string b) {
  9. queue<string> q;
  10. q.push(a);
  11. while (!q.empty()) {
  12. string a = q.front();
  13. q.pop();
  14. for (int i = 0;i < a.size();i++) {
  15.  
  16. for (int j = 0;j <= 9;j++) {
  17. if (i != 0 || j != 0) {
  18. string na = a;
  19. if (na[i] - '0' != j) {
  20. na[i] = j + '0';
  21. bool check = true;
  22. int temp = stoi(na);
  23. for (int i = 2;i*i <= temp;i++) {
  24. if (temp % i == 0) {
  25. check = false;
  26. }
  27. }
  28. if (check&&dist[temp] == -1) {
  29. dist[temp] = dist[stoi(a)] + 1;
  30. q.push(na);
  31. }
  32. }
  33. }
  34. }
  35. }
  36. }
  37. }
  38. int main() {
  39. int t;
  40. cin >> t;
  41. while (t--) {
  42. string a, b;
  43. cin >> a >> b;
  44. memset(dist, -1, sizeof(dist));
  45. dist[stoi(a)] = 0;
  46.  
  47. bfs(a, b);
  48. if (dist[stoi(b)] == -1) {
  49. cout << "Impossible" << endl;
  50. }
  51. else {
  52. cout << dist[stoi(b)] << endl;
  53. }
  54. }
  55. return 0;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement