码迷,mamicode.com
首页 > 其他好文 > 详细

ACdream 1025 bfs

时间:2016-05-29 00:53:29      阅读:221      评论:0      收藏:0      [点我收藏+]

标签:

Transform

Time Limit: 4000/2000MS (Java/Others) Memory Limit: 128000/64000KB (Java/Others)

Problem Description

One can transform xinto x+if dis divisor of x. Find out the minimum number of steps to transform a into b.

Input

Two integers a and b.

(1a,b105)

Output

The only integer denotes the minimum number of steps. Print 1if impossible.

Sample Input

1 6

Sample Output

3

Hint

1246or 1236

Source

ftiasch

Manager

 
题意:x变为 x+d d为x的因子  问由a变为b最少要多少步骤  无法到达 输出-1
 
题解: bfs处理 注意求因子的处理
         if(gg.x<=b&&vis[gg.x]==0)  注意两个比较式的先后顺序   vis数组 re多次 
 
 1 #include<iostream>
 2 #include<cstring>
 3 #include<cstdio>
 4 #include<queue>
 5 #include<stack>
 6 #include<cmath>
 7 #define ll long long 
 8 #define pi acos(-1.0)
 9 #define mod 1000000007
10 using namespace std;
11 int a,b;
12 struct node
13 {
14     int x;
15     int step;
16 }exm,gg;
17 queue<node> q;
18 int vis[100005];
19 void bfs(int st)
20 {
21     memset(vis,0,sizeof(vis));
22     while(!q.empty())
23      q.pop();
24    exm.x=st;
25    exm.step=0;
26    vis[st]=1;
27    q.push(exm);
28    while(!q.empty())
29    {
30        exm=q.front();
31        q.pop();
32        if(exm.x==b)
33        {
34            cout<<exm.step<<endl;
35            break;
36     }
37        for(int i=1;i<=sqrt(exm.x);i++)
38        {
39            if(exm.x%i==0)
40            {
41                gg.x=exm.x+i;
42                gg.step=exm.step+1;
43                if(gg.x<=b&&vis[gg.x]==0)
44                {
45                q.push(gg);
46                vis[gg.x]=1;
47             }
48             gg.x=exm.x+exm.x/i;
49                gg.step=exm.step+1;
50                if(gg.x<=b&&vis[gg.x]==0)
51                {
52                q.push(gg);
53                vis[gg.x]=1;
54             }
55         }
56     }
57    }  
58 }
59 int main()
60 {
61     while(scanf("%d %d",&a,&b)!=EOF)
62     {
63         if(a<=b)
64         bfs(a);
65         else
66         cout<<"-1"<<endl;
67     } 
68     return 0;
69 }

 

ACdream 1025 bfs

标签:

原文地址:http://www.cnblogs.com/hsd-/p/5538606.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!