poj 3126 Prime Path

#include <iostream>
#include <memory.h>
#include <queue>
using namespace std;
const int MAX = 100000;//竟然RE了三次,就是因为这里的MAX开小了! 
int step[MAX];
bool prime[MAX];
int base[4] = {1, 10, 100, 1000};

int main()
{
    int i, j, tc, num1, num2, n[5], newnum, oldnum, tmp;
    
    //先将素数表打出来 
    for (i = 0; i < MAX; i++)
         prime[i] = true;
    for (i = 2; i < MAX; i++){
        if (prime[i]){
           for (j = 2; j * i < MAX; j++){
               prime[i*j] = false;
           }
        }
    }
    
    //用bfs进行搜索与检测! 
    cin >> tc;
    while (tc--){
          cin >> num1 >> num2;
          memset(step, 0, sizeof(step));
          queue<int> p;
          p.push(num1);
          step[num1] = 1;
          while (!p.empty()){
                oldnum = p.front();
                if (oldnum == num2)  break;
                p.pop();
                tmp = oldnum;
                n[1] = tmp % 10;
                tmp /= 10; 
                n[2] = tmp % 10;
                tmp /= 10; 
                n[3] = tmp % 10;
                tmp /= 10; 
                n[4] = tmp % 10;
                //cout << n[1] << " " << n[2] << " " << n[3] << " " << n[4] << endl;
                for (i = 0; i < 10; i++){
                    newnum = oldnum - n[4] * 1000 + i * 1000;
                    if (i != 0 && prime[newnum] && !step[newnum]){
                        step[newnum] = step[oldnum] + 1;
                        p.push(newnum);
                    }
                    for (j = 1; j < 4; j++){
                        newnum = oldnum - n[j] * base[j-1] + i * base[j-1];
                        if (prime[newnum] && !step[newnum]){
                            step[newnum] = step[oldnum] + 1;
                            p.push(newnum);
                        }
                    } 
                }
          }
          cout << step[num2] - 1 << endl;
    }
    
    system("pause");
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值