当前位置:编程学习 > C/C++ >>

ACdream 1024

bfs可以过的,只是我太粗心了,把num写成step了,然后一直错,找了2个多小时,真心好郁闷,害的后来没心情做题目了
[cpp] 
/**************************************************************
    Problem: 1024
    User: yp0408100207
    Language: C++
    Result: Accepted
    Time:670 ms
    Memory:1884 kb
****************************************************************/ 
 
#include<iostream> 
#include <cmath> 
#include <cstdio> 
#include <queue> 
#include <string.h> 
using namespace std; 
  
int b; 
bool flag[100003]; 
  
struct N 

    int num,step; 
}; 
  
int bfs(int a) 

    memset(flag,false,sizeof(flag)); 
    N now,next; 
    now.num=a; 
    now.step=0; 
    queue<N> q; 
    q.push(now); 
    int i; 
    int temp; 
    while(!q.empty()) 
    { 
        now=q.front(); 
        if (now.num==b) 
        { 
            return now.step; 
        } 
        q.pop(); 
        temp=(int)sqrt((double)now.num); 
        for (i=1;i<=temp;i++) 
        { 
            if(now.num%i) continue; 
  
            int aa=now.num/i; 
              
            next.num=now.num+i; 
            if(next.num<=b&&!flag[next.num]) 
            { 
                next.step=now.step+1; 
                flag[next.num]=true;//flag[next.step]=true;哎,弄了好久 
                q.push(next); 
            } 
  
            if(aa==i) continue; 
  
            next.num=now.num+aa; 
            if(next.num<=b&&!flag[next.num]) 
            { 
                next.step=now.step+1; 
                flag[next.num]=true; 
                q.push(next); 
            } 
        } 
    } 
    return -1; 

  
int main() 

    int a; 
    while (scanf("%d%d",&a,&b)!=EOF) 
    { 
        if(a==b) 
        { 
            printf("0\n"); 
            continue; 
        } 
        if (a>b) 
        { 
            printf("-1\n"); 
            continue; 
        } 
        printf("%d\n",bfs(a)); 
    } 
    return 0; 

 

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,