hdu1973 Prime Path
来源:互联网 发布:网易电台录制软件 编辑:程序博客网 时间:2024/04/29 06:27
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1973
题意:从一个素数变到另一个素数,一次只能动一位,一次的费用是1,求最小费用。
思路:bfs水题,但是注意第一位不能为0,否则第二个样例的答案是5
#include<iostream>#include<cstdio>#include<cstring>#include<string>#include<algorithm>#include<cmath>#include<queue>#define maxn 100000using namespace std;int n, m;bool prime[maxn];bool vis[maxn];int add[4] = {1, 10, 100, 1000};int num[25];int dis[maxn];void pre(){ fill(prime, prime + maxn, 1); prime[0] = prime[1] = 0; for(int i = 2; i < maxn; i++) { if(prime[i]) { int j = i << 1; while(j < maxn) { prime[j] = 0; j += i; } } }}int C(int num, int n){ int x = n / add[num]; int y = x % 10; return n - y * add[num];}bool Bfs(){ memset(vis, 0, sizeof(vis)); memset(dis, -1, sizeof(dis)); queue<int> Q; Q.push(n); vis[n] = 1; dis[n] = 0; while(!Q.empty()) { int pre = Q.front(); Q.pop(); if(pre == m) { cout << dis[m] << endl; return 1; } for(int i = 0; i < 4; i++) { int tmp = C(i, pre); for(int j = 0; j <= 9; j++) { int cur = tmp + j * add[i]; if(cur >= 1000 && prime[cur] && !vis[cur]) { Q.push(cur); dis[cur] = dis[pre] + 1; vis[cur] = 1; } } } } return 0;}int main(){ pre(); int t; cin >> t; while(t--) { scanf("%d %d", &n, &m); if(!Bfs()) { cout << "Impossible" << endl; } } return 0;}
阅读全文
0 0
- hdu1973 || poj3126 Prime Path
- hdu1973 Prime Path
- Prime Path (HDU1973/POJ3126)(B)
- Prime Path
- Prime Path
- PRIME PATH
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- Prime Path
- 线段树之扫描线之周长并
- JNI源码分析 (并实现JNI动态注册)
- Python知识点
- LightSwitch中自动编号的生成
- 算法——Permutation
- hdu1973 Prime Path
- SPOJ LCS2 Longest Common Substring II
- 单张相片的后方交会
- 九度OJ题目1046:求最大值
- 1.3数据库系统结构
- 开通博客
- 31. Next Permutation
- 认识HDFS分布式文件系统
- 数据结构 1 概念