poj 3126 Prime Path (bfs)

来源:互联网 发布:大数据面临的问题评价 编辑:程序博客网 时间:2024/06/04 18:52

一学期前看题解敲的:

#include<iostream>#include<queue>#include<cstring>#include<cstdlib>#include<cmath>using namespace std;int n;int prime[10010] = {0};int book[10010];int step[10010];int bfs(int sou, int des) {queue<int> q;memset(book, 0, sizeof(book));memset(step, 0, sizeof(step));q.push(sou);book[sou] = 1;while(!q.empty()) {int x = q.front();q.pop();int t[4];t[0] = x / 1000;t[1] = x % 1000 / 100;t[2] = x % 100 / 10;t[3] = x % 10;int i, j, tmp;for(i = 0; i < 4; i++) {tmp = t[i];for(j = 0; j < 10; j++) {if(tmp != j) {t[i] = j;int y = t[3] + t[2] * 10 + t[1] * 100 + t[0] * 1000;if(!book[y] && prime[y]) {q.push(y);step[y] = step[x] + 1;book[y] = 1;}if(y == des) return step[y];}}t[i] = tmp;}if(x == des) return step[x];}return -1;}int main() {prime[0] = prime[1] = 1;int i, j;for(i = 0; i < 10010; i++) {prime[i] = 1;}for(i = 2; i <= sqrt(10010.0); i++) {if(prime[i]) {for(j = i + i; j < 10010; j += i) {prime[j] = 0;}}}for(i = 0; i < 1000; i++) {prime[i] = 0;}cin >> n;while(n--) {int a, b;cin >> a >> b;int t = bfs(a, b);if(t == -1) cout << "Impossible" << endl;else cout << t << endl;}return 0;}


一学期后自己写的:

#include <iostream>#include <cstdio>#include <cstring>#include <algorithm>#include <queue>#include <cmath>using namespace std;int isprime[10010];int vis[10010];void init() {int i, j;for(i = 0; i < 10000; i++) {isprime[i] = 1;}isprime[0] = isprime[1] = 0;for(i = 2; i <= sqrt(10000); i++) {if(isprime[i] == 1) {for(j = i + i; j < 10000; j += i) {isprime[j] = 0;}}}for(i = 0; i <= 999; i++) {isprime[i] = 0;}}int a, b;struct node {int num, step;};int bfs() {queue<node> q;node now, next;now.num = a, now.step = 0;q.push(now);vis[now.num] = 1;while(!q.empty()) {now = q.front();q.pop();int i, j;if(now.num == b) {return now.step;}for(i = 0; i < 4; i++) {for(j = 0; j <= 9; j++) {if(now.num % (int)pow(10, i + 1) / (int)pow(10, i) == j) continue;int t1 = now.num / (int)pow(10, i + 1);int t2 = now.num % (int)pow(10, i);next.num = t1 * (int)pow(10, i + 1) + j * (int)pow(10, i) + t2;next.step = now.step + 1;if(vis[next.num] == 0 && isprime[next.num] == 1) {vis[next.num] = 1;q.push(next);}}}}return -1;}int main() {init();    int n;    scanf("%d", &n);    while(n--) {    memset(vis, 0, sizeof(vis));    scanf("%d %d", &a, &b);    printf("%d\n", bfs());}    return 0;}

说明还是有提高的。。。多复习。

0 0
原创粉丝点击