Hdu 1104 Remainder[Bfs]
来源:互联网 发布:matlab 矩阵乘法输出 编辑:程序博客网 时间:2024/05/30 23:42
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1104
题意:给三个数 n,k,m;n可以 + ,-,*,%m,得到的值还给n,问最少多少步,可以使现在的n%k = (最初的n + 1)%k。
他对取余的定义为取余后必须为正。。
这个问题,看似很是简单。。没有什么问题。但是都会犯一个错误。。
我们知道+,-,*,都是满足同余定理的。。但是%就不满足了。。
也就是说(a%b)%c!=((a%c)%(b%c))%c。为什么。我们可以任意是的举一个例子,当c<b的时候。。
那么,对于该题目,我们可以的做法是什么呢?
我们可以用k*m来标记状态,这样就避免了出现错误了。。。个中体会,还要自己思考一下。。
Code:
#include <cstdio>#include <cmath>#include <cstring>#include <string>#include <algorithm>#include <queue>#include <iostream>using namespace std;const int N = 1e6 + 5;bool vis[N];struct Node{ int x; int step; string way; Node(){} Node(int a, int b, string c){ x = a; step = b; way = c; }};int n, k, m;int Mod(int x, int y){ return (x % y + y) % y;}void bfs(){ memset(vis, 0, sizeof(vis)); queue<Node> q; q.push(Node(n, 0, "")); while(!q.empty()){ Node now = q.front(); q.pop();// printf("now = %d\n", now.x); if(Mod(now.x, k) == Mod(n + 1, k)){ printf("%d\n", now.step); cout << now.way << endl; return ; } if(!vis[Mod(now.x + m, k * m)]){ q.push(Node(Mod(now.x + m, k * m), now.step + 1, now.way + '+')); vis[Mod(now.x + m, k * m)] = true; } if(!vis[Mod(now.x - m, k * m)]){ q.push(Node(Mod(now.x - m, k * m), now.step + 1, now.way + '-')); vis[Mod(now.x - m, k * m)] = true; } if(!vis[Mod(now.x * m, k * m)]){ q.push(Node(Mod(now.x * m, k * m), now.step + 1, now.way + '*')); vis[Mod(now.x * m, k * m)] = true; } if(!vis[Mod(Mod(now.x, m), k * m)]){ q.push(Node(Mod(Mod(now.x, m), k * m), now.step + 1, now.way + '%')); vis[Mod(now.x, k * m)] = true; } } puts("0"); return ;}int main(){// cout << 939134 % 859 << endl;// freopen("1.txt", "r", stdin); while(scanf("%d %d %d", &n, &k, &m) && (n || k || m)){ bfs(); } return 0;}
总体来说,这还是一个比较简单的bfs。但是,小有不注意就会发生,如上面的错误。。
0 0
- hdu 1104 Remainder BFS
- Hdu 1104 Remainder[Bfs]
- 【bfs】hdu 1104 Remainder
- hdu 1104 Remainder(BFS)
- hdu 1104 remainder bfs+数论
- HDU 1104 Remainder (BFS)
- HDU 1104题Remainder(bfs)
- hdu 1104 Remainder(BFS+数论)
- HDU 1104 Remainder(BFS 同余定理)
- 1104 Remainder(数论+bfs)
- HDU 1104 Remainder( BFS(广度优先搜索))
- hdu 1104/poj 2426 Remainder(数论,BFS)
- HDU 1104 Remainder
- hdu 1104 Remainder
- HDU - 1104 Remainder 搜索
- HDU 1104 Remainder
- HDU 1104 Remainder
- Remainder hdu 1104
- I could be the one!
- 垃圾收集器
- 并发编程--在同步代码中使用条件实现生产者消费者
- JBPM4.4与DB2整合
- Android 和 iOS 实现路由(route)系统。
- Hdu 1104 Remainder[Bfs]
- 翻转句子中单词的顺序
- jsp中include出现的问题
- 南京IT企业环境之最深心得体会
- [Windows PowerShell01]-基本概念
- linux设备驱动编写基础
- 算法竞赛入门经典第二章习题答案
- liux 命令备忘录
- javascript document.compatMode介绍