POJ 3126, Prime Path
2011-10-29 21:32
330 查看
View Code
#include <iostream> #include <queue> #include <cstdio> #include <cstring> using namespace std; int main() { //init prime table bool prime[10001]; memset(prime,1,sizeof (prime)); prime[0] = false;prime[1] = false; for (int i = 2; i < 5000; ++i) { int k = 2; int next; while((next = (k++) * i) < 10000) prime[next] = false; } int cases; cin >> cases; int beg, end; int step; int visited[10001]; int base[4]= {1, 10, 100, 1000}; for (int c = 0; c < cases; ++c) { scanf("%d %d", &beg, &end); memset(visited, -1, sizeof(visited)); queue<int> q; q.push(beg); visited[beg] = 0; step = -1; while (!q.empty()) { int cur = q.front(); q.pop(); if (cur == end) { step = visited[cur]; break; } for (int i = 0; i < 4; ++i) { for (int j = 0; j < 10; ++j) { int l = cur / (base[i] * 10); int r = cur % base[i];//base[i]数组很巧妙很好。值得学习 int num = l * base[i] * 10 + j * base[i] + r; if (num > 1000 && num != cur && prime[num] == true && visited[num] == -1) { q.push(num); visited[num] = visited[cur] + 1; } } } } if (step == -1)cout << "Impossible\n"; else cout << step << endl; } return 0; }
相关文章推荐
- POJ 3126 Prime Path BFS
- POJ 3126 Prime Path(BFS 数字处理)
- POJ 3126 Prime Path
- POJ 3126 Prime Path 素数筛,bfs
- Poj 3126 Prime Path
- POJ 3126 - Prime Path
- POJ - 3126 Prime Path(BFS)
- Prime Path(POJ 3126)解题报告
- Prime Path POJ - 3126 bfs
- poj 3126 Prime Path
- POJ 3126 Prime Path( 广搜 )
- Prime Path(POJ 3126 BFS)
- POJ 3126 Prime Path
- POJ 3126 Prime Path(BFS)
- 【poj】3126 Prime Path(bfs)
- poj 3126 Prime Path(bfs)
- POJ 3126 Prime Path
- POJ-3126 Prime Path (BFS)
- poj 3126 Prime Path bfs求最短路
- POJ 3126 Prime Path (BFS)