POJ 3126 Prime Path(bfs)
来源:互联网 发布:淘宝人工服务号码多少 编辑:程序博客网 时间:2024/05/16 00:38
题意:
给定两个4位的质数a和b,从a开始每次只能改变a的一个数字,并且改完后的a还是质数,求a最少经过几次变换能得到b…..
比如1033变到8179最少需要6次,过程如下
1033
1733
3733
3739
3779
8779
8179
解析:
先打印素数表,然后进行bfs。
AC代码
#include <cstdio>#include <cstring>#include <algorithm>#include <cmath>#include <cstdlib>using namespace std;typedef long long ll;const int INF = 0x3f3f3f3f;const int N = 20;const int dx[] = {-1, 0, 1, 0, 0};const int dy[] = { 0,-1, 0, 1, 0};int grid[N][N], state[N][N], tmp[N][N], rec[N][N];int n, m, ans;void flip(int x, int y) { tmp[x][y] = 1; int nx, ny; for(int i = 0; i < 5; i++) { nx = x+dx[i]; ny = y+dy[i]; state[nx][ny] = !state[nx][ny]; }}bool isEmpty(int n) { for(int j = 1; j <= m; j++) { if(state[n][j] == 1) return false; } return true;}void solve(int st) { memcpy(state, grid, sizeof(grid)); memset(tmp, 0, sizeof(tmp)); int cnt = 0; for(int j = 0; j < m; j++) { if((st>>j) & 1) { flip(1, j+1); cnt++; } } for(int i = 2; i < n; i++) { for(int j = 1; j <= m; j++) { if(state[i-1][j]) { flip(i, j); cnt++; } } } if(isEmpty(n) && cnt < ans) { ans = cnt; memcpy(rec, tmp, sizeof(tmp)); }}int main() { while(scanf("%d%d", &n, &m) != EOF) { memset(grid, 0, sizeof(grid)); for(int i = 1; i <= n; i++) { for(int j = 1; j <= m; j++) { scanf("%d", &grid[i][j]); } } ans = INF; int end = 1 << m; for(int st = 0; st < end; st++) solve(0); if(ans == INF) puts("IMPOSSIBLE"); else { for(int i = 1; i <= n; i++) { printf("%d", rec[i][1]); for(int j = 2; j <= m; j++) printf(" %d", rec[i][j]); puts(""); } } } return 0;}
0 0
- poj poj 3126 Prime Path(BFS)
- poj 3126 Prime Path(bfs搜索)
- POJ 3126 Prime Path (BFS)
- poj 3126 Prime Path(BFS)
- poj 3126 Prime Path (bfs)
- POJ 3126 Prime Path(BFS算法)
- Prime Path (poj 3126 bfs)
- POJ 3126 Prime Path(BFS)
- POJ 3126 - Prime Path(BFS)
- poj 3126 Prime Path(BFS)
- POJ 3126 Prime Path(BFS)
- POJ 3126 Prime Path (bfs、埃氏筛法)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path(bfs)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path (BFS)
- POJ 3126 Prime Path(BFS)
- VC++文件操作之最全篇
- 【机房收费系统】——泛型的理解
- cmake
- Delphi 禁用TEdit右键菜单及复制粘贴
- APUE协同进程的讨论
- POJ 3126 Prime Path(bfs)
- keytool生成证书与Tomcat SSL配置
- android的TaskAffinity属性
- automake
- HMM MATLAB Toolbox应用
- cocos2dx Android接入芒果插屏广告
- VC++文件操作之最全篇
- edittext种类大全
- linux下socket编程实例