Advertisement
Abrar_Al_Samit

Prime Path (SPOJ)

Feb 11th, 2021
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.56 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. bool primeSieve[100000], vis[100000];
  5. int d[100000];
  6. void preprocess() {
  7.     memset(primeSieve, true, sizeof primeSieve);
  8.     for(int i=2; i<100000; i++) {
  9.         if(!primeSieve[i]) continue;
  10.         for(int j=2; i*j<100000; j++)
  11.             primeSieve[i*j] = false;
  12.     }
  13. }
  14. bool valid (int curN, int changedN) {
  15.  
  16.     bool ret = changedN < 100000 && changedN > 999;
  17.     if(!ret) return ret;
  18.     ret &= primeSieve[changedN];
  19.  
  20.     int changeCnt = 0;
  21.     string s = to_string(curN), t = to_string(changedN);
  22.     for(int i=0; i<4; i++) {
  23.         changeCnt += s[i]!=t[i];
  24.     }
  25.     ret &= changeCnt==1;
  26.  
  27.     return ret;
  28. }
  29. int fastpow(int y) {
  30.     return (int)pow(10, y);
  31. }
  32. void Test_Case() {
  33.     memset(vis, false, sizeof vis);
  34.     int n, m; cin >> n >> m;
  35.     queue<int>q;
  36.     q.push(n);
  37.     d[n] = 0;
  38.     vis[n] = 1;
  39.     while((int)q.size()) {
  40.         int curN = q.front(); q.pop();
  41.         for(int i=0; i<4; i++) {
  42.             for(int j=0; j<10; j++) {
  43.                 int changedN1 = curN+fastpow(i)*j;
  44.                 int changedN2 = curN-fastpow(i)*j;
  45.                 if(valid(curN, changedN1)) {
  46.                     if(vis[changedN1]==0) {
  47.                         q.push(changedN1);
  48.                         d[changedN1] = 1+d[curN];
  49.                         vis[changedN1] = 1;
  50.                     }
  51.                 }
  52.                 if(valid(curN, changedN2)) {
  53.                     if(vis[changedN2]==0) {
  54.                         q.push(changedN2);
  55.                         d[changedN2] = 1+d[curN];
  56.                         vis[changedN2] = 1;
  57.                     }
  58.                 }
  59.             }
  60.         }
  61.     }
  62.  
  63.     cout << d[m] << "\n";
  64. }
  65. int main() {
  66.     preprocess();
  67.     int t; cin >> t;
  68.     for(int i=1; i<=t; i++)
  69.     Test_Case();
  70.    
  71.     return 0;
  72. }
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement