TOJ : 2648. Prime Path

来源:互联网 发布:淘宝历史最低价插件 编辑:程序博客网 时间:2024/05/04 12:04

题目 : http://acm.tju.edu.cn/toj/showp2648.html

做的时候感觉就是道水bfs,但是却因为itoa这CE了几次,OJ上交的时候只能用最笨的法子

#include "cstdio"#include "cstring"#include "queue"#include "stdlib.h"#define maxn 10000using namespace std;bool is[maxn];int n, tar, v[maxn];void make() {memset(is, 0, sizeof(is));for (int i = 2; i < maxn; i++) {if (!is[i]) {for (int j = i + i; j < maxn; j += i)is[j] = true;}}}void bfs() {queue<int> Q;while (!Q.empty()) Q.pop();memset(v, -1, sizeof(v));Q.push(n);v[n] = 0;while (!Q.empty()) {int t = Q.front(); Q.pop();char s[5], ss[5];itoa(t, s, 10);for (int i = 0; i < 4; i++) {int tt = s[i] - '0';strcpy(ss, s);for (int j = 0; j <= 9; j++) {if (j == tt || (!i && !j)) continue;ss[i] = j + '0';int at = atoi(ss);if (is[at]) continue;if (v[at] == -1 || v[at] > v[t] + 1) {v[at] = v[t] + 1;Q.push(at);}if (at == tar) return;}}}}int main() {int cas;make();scanf("%d", &cas);while (cas--) {scanf("%d%d", &n, &tar);bfs();if (v[tar] != -1) printf("%d\n", v[tar]);else printf("Impossible\n"); }}


0 0
原创粉丝点击