Poj3126




import java.io.BufferedInputStream;
import java.util.LinkedList;
import java.util.Scanner;

/**
* @author NC
* poj3126
* 筛素数+bfs
* 最初判断素数是打算一个一个按照基本定义去判断,后来想到当case多的时候,有很多重复的操作
* 所以就找到了线性筛素数的模版,简单改了一下,得到了一张素数表,这样应该会快一点
* 而作bfs时
* 发现,每一步有39个方向.....如果要调试的话,应该很麻烦
* 果然当写完程序时,测试的样例都过不了,郁闷啊......
* 最后发现一个循环少了个=号...无语
*/
public class Poj3126 {

static boolean[] isPrime = Prime.getPrimes(10000);

public static void main(String[] args) {

Scanner scan = new Scanner(new BufferedInputStream(System.in));
int cas = scan.nextInt();
for (int i = 1; i <= cas; i++) {
int start = scan.nextInt();
int end = scan.nextInt();
boolean[] isVisited = new boolean[10000];
int[] step = new int[10000];
LinkedList<Integer> queue = new LinkedList();
queue.addLast(start);
isVisited[start] = true;
while (!queue.isEmpty()) {
int current = queue.pop();
if (current == end) {
break;
}
for (int j = 0; j <= 9; j++) {//少了等号
int next1 = getNext(1, j, current);
int next2 = getNext(2, j, current);
int next3 = getNext(3, j, current);
int next4 = getNext(4, j, current);
if (!isVisited[next1]) {
queue.addLast(next1);
step[next1] = step[current] + 1;
isVisited[next1] = true;
}
if (!isVisited[next2]) {
queue.addLast(next2);
step[next2] = step[current] + 1;
isVisited[next2] = true;
}
if (!isVisited[next3]) {
queue.addLast(next3);
step[next3] = step[current] + 1;
isVisited[next3] = true;
}
if (!isVisited[next4]) {
queue.addLast(next4);
step[next4] = step[current] + 1;
isVisited[next4] = true;
}
}
}
System.out.println(step[end]);
}
}

public static int getNext(int flag, int i, int current) {
int next = 0;
if (flag == 1) {
if (i == 0) {
return current;
}
next = current % 1000 + i * 1000;
}
if (flag == 2) {
int t = current / 1000;
next = t * 1000 + current % 1000 % 100 + i * 100;
}
if (flag == 3) {
int t = current / 100;
int tt = current % 10;
next = t * 100 + i * 10 + tt;
}
if (flag == 4) {
next = current / 10 * 10 + i;

}
if (!isPrime[next]) {
return current;
}
return next;
}
}
/*
线性筛素数的一个方法,返回一个素数表
*/

class Prime {

public static boolean[] getPrimes(int n) {
int i, j, k, x;
boolean[] a = new boolean[n];
n++;
n /= 2;
int[] b = new int[(n + 1) * 2];
a[2] = true;
a[3] = true;
for (i = 1; i <= 2 * n; i++) {
b[i] = 0;
}
for (i = 3; i <= n; i += 3) {
for (j = 0; j < 2; j++) {
x = 2 * (i + j) - 1;
while (b[x] == 0) {
a[x] = true;
for (k = x; k <= 2 * n; k += x) {
b[k] = 1;
}
}
}
}
return a;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值