POJ 3126 Prime Path
来源:互联网 发布:linux locale 命令 编辑:程序博客网 时间:2024/05/04 09:57
题目大意:
给定两个素数a,b, 要求每次改变a中的一个数得到一个新的素数a1,再对a1中的一个数改变得到新的素数a2,问循环下去能否得到素数b.
思路:
BFS 每次改变当前素数的一个值,判断是否为素数即可,注意前导0的问题
#include <iostream>#include <cstring>#include <queue>using namespace std;bool is_prime[10000];int n, k;int vis[10000];struct node{ int prime; int cnt;};int BFS(){ queue <node> q; node cur,next; cur.prime = n; cur.cnt = 0; q.push(cur); while (!q.empty()) { cur = q.front(); q.pop(); if (cur.prime == k) return cur.cnt; int a[4],t[4]; int term = cur.prime; for (int i = 3; i >= 0; --i) { a[i] = term % 10; term /= 10; t[i] = a[i]; } for (int i = 0; i != 4; ++i) //枚举个十百千位 for (int j = 0; j != 10; ++j) // 枚举0-9去改变个十百千位得到新的素数 { if (i == 0 && j == 0) continue; //前导0的情况 a[i] = j; next.prime = a[0]*1000+a[1]*100+a[2]*10+a[3]; if (next.prime < 10000 && is_prime[next.prime] == true && !vis[next.prime]) { next.cnt = cur.cnt + 1; vis[next.prime] = 1; q.push(next); } a[i] = t[i]; } } return -1;}int main(){ memset(is_prime,true,sizeof(is_prime)); is_prime[0] = false, is_prime[1] = false; //is_prime 存放素数 for (int i = 2; i != 10000; ++i) if (is_prime[i] == true) for (int j = i*2; j < 10000; j+=i) is_prime[j] = false; int ss; cin >> ss; while (ss--) { cin >> n >> k; memset(vis,0,sizeof(vis)); int t = BFS(); if (t == -1) cout << "Impossible" << endl; else cout << t << endl; } return 0;}
0 0
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- poj 3126Prime Path
- POJ -3126-Prime Path
- POJ 3126 Prime Path
- poj 3126 Prime Path
- POJ 3126 - Prime Path
- POJ 3126 Prime Path
- poj 3126 prime path
- POJ 3126 Prime Path
- Prime Path poj 3126
- POJ 3126 Prime Path
- poj 3126 Prime Path
- POJ 3126 Prime Path
- poj 3126 Prime path
- poj - 3126 - Prime Path
- POJ 3126 Prime Path
- POJ 3126 Prime Path
- Android基础(数据操作)
- hdu 1071 - The area(解题报告)
- find和xargs学习笔记
- 详解如何调试xcode程序
- RFID读卡器与OK6410通信成功
- POJ 3126 Prime Path
- LeetCode(216)Combination Sum III
- HDOJ 5099 Comparison of Android versions(字符串模拟)
- 今日总结
- <Android Framework 之路>Android5.1 Camera Framework(一)
- [Java]Invert Binary Tree翻转二叉树
- 小小菜之Cocos2d-x游戏开发旅程——项目实例:贪吃蛇(4)
- Oracle_cursor_shared 参数解释
- Codeforces Round #316 (Div. 2)dfs序