HDU 1104 BFS

来源:互联网 发布:mac osx使用教程 编辑:程序博客网 时间:2024/06/08 11:45

这里的 % 不能直接使用 因为,题目中的%是数论中的取模.

 %: 如果 a = b * q + r (q > 0 and 0 <= r < q)  则 a % q = r 

 这里必须保证r>0, 而直接对一个负数进行%时则会出现负数.


用% (k*m)  记录判重


#include "stdio.h"#include "string.h"#include "iostream"#include "algorithm"#include "queue"using namespace std;struct node{    int n;    queue<char>op;} ;int mod,key,k,m,n;int hash[1000010];int  bfs(){    memset(hash,0,sizeof(hash));    queue<node>q;    node cur,next;    n=(n%mod)+mod;    key=(n+1)%k;    cur.n=n;    q.push(cur);        hash[cur.n]=1;    while (!q.empty())    {        cur=q.front();        q.pop();        if (cur.n%k==key)         {            printf("%d\n",cur.op.size());                        while(!cur.op.empty())              {                  printf("%c",cur.op.front());                cur.op.pop();              }              printf("\n");              return 1;        }        next=cur;        next.n=(cur.n+m)%mod;            if (hash[next.n]==0)        {            hash[next.n]=1;            next.op.push('+');            q.push(next);        }        next=cur;        next.n=((cur.n-m)%mod+mod)%mod;        if (hash[next.n]==0)        {            hash[next.n]=1;            next.op.push('-');            q.push(next);        }        next=cur;        next.n=(cur.n*m)%mod;        if ( hash[next.n]==0)        {            hash[next.n]=1;            next.op.push('*');            q.push(next);        }        next=cur;        next.n=(cur.n%m)%mod;        if (hash[next.n]==0)        {            hash[next.n]=1;            next.op.push('%');            q.push(next);        }    }    return 0;}int main(){    while (scanf("%d%d%d",&n,&k,&m)!=EOF)    {        if (n+m+k==0) break;        mod=k*m;        if (bfs()==0)            printf("0\n");    }    return 0;}


0 0